How to copy a file to another path?

后端 未结 9 1015
长发绾君心
长发绾君心 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:37

    File::Copy will copy the file to the destination folder and File::Move can both move and rename a file.

    0 讨论(0)
  • 2020-11-27 05:38
    File.Move(@"c:\filename", @"c:\filenamet\filename.txt");
    
    0 讨论(0)
  • 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);
            }
        }        
    
    0 讨论(0)
提交回复
热议问题