Wednesday, June 17, 2026

C# Copy file from source path to target path

There are two versions of Copy methods of File class to copy a file to a target file.
  • public static void Copy(string sourceFileName, string destFileName);
  • public static void Copy(string sourceFileName, string destFileName, bool overwrite);

Example
class Demo
{
    static void Main()
    {
        var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string sourcePath = Path.Combine(documents, "sample.txt");
        string targetPath = Path.Combine(documents, "sample_copy.txt");
        try
        {
            File.Copy(sourcePath, targetPath, false);// true for overwrite

        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine(ex.Message);
        }
        catch (System.IO.IOException ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

No comments:

Post a Comment

Hot Topics