How to copy a file to another path?

后端 未结 9 1029
长发绾君心
长发绾君心 2020-11-27 04:59

I need to copy a file to another path, leaving the original where it is.

I also want to be able to rename the file.

Will FileInfo\'s CopyTo method work?

9条回答
  •  清歌不尽
    2020-11-27 05:39

    This is what I did to move a test file from the downloads to the desktop. I hope its useful.

    private void button1_Click(object sender, EventArgs e)//Copy files to the desktop
        {
            string sourcePath = @"C:\Users\UsreName\Downloads";
            string targetPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string[] shortcuts = {
                "FileCopyTest.txt"};
    
            try
            {
                listbox1.Items.Add("Starting: Copy shortcuts to dektop.");
                for (int i = 0; i < shortcuts.Length; i++)
                {
                    if (shortcuts[i]!= null)
                    {
                        File.Copy(Path.Combine(sourcePath, shortcuts[i]), Path.Combine(targetPath, shortcuts[i]), true);                        
                        listbox1.Items.Add(shortcuts[i] + " was moved to desktop!");
                    }
                    else
                    {
                        listbox1.Items.Add("Shortcut " + shortcuts[i] + " Not found!");
                    }
                }
            }
            catch (Exception ex)
            {
                listbox1.Items.Add("Unable to Copy file. Error : " + ex);
            }
        }        
    

提交回复
热议问题