[c#] How to copy a file to another path?

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?

This question is related to c# file-io

The answer is


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


string directoryPath = Path.GetDirectoryName(destinationFileName);

// If directory doesn't exist create one
if (!Directory.Exists(directoryPath))
{
DirectoryInfo di = Directory.CreateDirectory(directoryPath);
}

File.Copy(sourceFileName, destinationFileName);

File.Move(@"c:\filename", @"c:\filenamet\filename.txt");

Old Question,but I would like to add complete Console Application example, considering you have files and proper permissions for the given folder, here is the code

 class Program
 {
    static void Main(string[] args)
    {
        //path of file
        string pathToOriginalFile = @"E:\C-sharp-IO\test.txt";

        
        //duplicate file path 
        string PathForDuplicateFile = @"E:\C-sharp-IO\testDuplicate.txt";
         
          //provide source and destination file paths
        File.Copy(pathToOriginalFile, PathForDuplicateFile);

        Console.ReadKey();

    }
}

Source: File I/O in C# (Read, Write, Delete, Copy file using C#)


Yes. It will work: FileInfo.CopyTo Method

Use this method to allow or prevent overwriting of an existing file. Use the CopyTo method to prevent overwriting of an existing file by default.

All other responses are correct, but since you asked for FileInfo, here's a sample:

FileInfo fi = new FileInfo(@"c:\yourfile.ext");
fi.CopyTo(@"d:\anotherfile.ext", true); // existing file will be overwritten

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);
        }
    }        

I tried to copy an xml file from one location to another. Here is my code:

public void SaveStockInfoToAnotherFile()
{
    string sourcePath = @"C:\inetpub\wwwroot";
    string destinationPath = @"G:\ProjectBO\ForFutureAnalysis";
    string sourceFileName = "startingStock.xml";
    string destinationFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xml"; // Don't mind this. I did this because I needed to name the copied files with respect to time.
    string sourceFile = System.IO.Path.Combine(sourcePath, sourceFileName);
    string destinationFile = System.IO.Path.Combine(destinationPath, destinationFileName);

    if (!System.IO.Directory.Exists(destinationPath))
       {
         System.IO.Directory.CreateDirectory(destinationPath);
       }
    System.IO.File.Copy(sourceFile, destinationFile, true);
}

Then I called this function inside a timer_elapsed function of certain interval which I think you don't need to see. It worked. Hope this helps.


Have a look at File.Copy()

Using File.Copy you can specify the new file name as part of the destination string.

So something like

File.Copy(@"c:\test.txt", @"c:\test\foo.txt");

See also How to: Copy, Delete, and Move Files and Folders (C# Programming Guide)


You could also use File.Copy to copy and File.Move to rename it afterwords.

// Copy the file (specify true or false to overwrite or not overwrite the destination file if it exists.
File.Copy(mySourceFileAndPath, myDestinationFileAndPath, [true | false]);

// EDIT: as "astander" notes correctly, this step is not necessary, as File.Copy can rename already...
//       However, this code could be adapted to rename the original file after copying
// Rename the file if the destination file doesn't exist. Throw exception otherwise
//if (!File.Exists(myRenamedDestinationFileAndPath))
//    File.Move(myDestinationFileAndPath, myRenamedDestinationFileAndPath);
//else
//    throw new IOException("Failed to rename file after copying, because destination file exists!");

EDIT
Commented out the "rename" code, because File.Copy can already copy and rename in one step, as astander noted correctly in the comments.

However, the rename code could be adapted if the OP desired to rename the source file after it has been copied to a new location.


TO Copy The Folder I Use Two Text Box To Know The Place Of Folder And Anther Text Box To Know What The Folder To Copy It And This Is The Code

MessageBox.Show("The File is Create in The Place Of The Programe If you Don't Write The Place Of copy And You write Only Name Of Folder");// It Is To Help The User TO Know
          if (Fromtb.Text=="")
        {
            MessageBox.Show("Ples You Should Write All Text Box");
            Fromtb.Select();
            return;
        }
        else if (Nametb.Text == "")
        {
            MessageBox.Show("Ples You Should Write The Third Text Box");
            Nametb.Select();
            return;
        }
        else if (Totb.Text == "")
        {
            MessageBox.Show("Ples You Should Write The Second Text Box");
            Totb.Select();
            return;
        }

        string fileName = Nametb.Text;
        string sourcePath = @"" + Fromtb.Text;
        string targetPath = @"" + Totb.Text;


        string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
        string destFile = System.IO.Path.Combine(targetPath, fileName);


        if (!System.IO.Directory.Exists(targetPath))
        {
            System.IO.Directory.CreateDirectory(targetPath);
            //when The User Write The New Folder It Will Create 
            MessageBox.Show("The File is Create in "+" "+Totb.Text);
        }


        System.IO.File.Copy(sourceFile, destFile, true);


        if (System.IO.Directory.Exists(sourcePath))
        {
            string[] files = System.IO.Directory.GetFiles(sourcePath);


            foreach (string s in files)
            {
                fileName = System.IO.Path.GetFileName(s);
                destFile = System.IO.Path.Combine(targetPath, fileName);
                System.IO.File.Copy(s, destFile, true);

            }
            MessageBox.Show("The File is copy To " + Totb.Text);

        }