Programmer's Corner - C# Source Code Sample

Backup and Security Solutions 10% off all products with promo code: VISI-P1YR
Get the Programmer's Corner FireFox Search Plug-In

File Copy Using File.Copy Method in C# - C#

Mark Schweikert

http://www.programmers-corner.com

modusponens@toadmail.com

         

         

Copying a file using the File.Copy Method from the .Net framework.





using System;
using System.IO;

class FileCopy
{
  public static void Main() 
  {
    string sourceFile = @"C:\SourceFile.txt";
    string destinationFile = @"C:\DestinationFile.txt";

    //Attempt file copy
    try 
    {
      //Delete destinationFile for overwrite,
      //causes exception if already exists.
      File.Delete(destinationFile);

      File.Copy(sourceFile, destinationFile);
       
      //Successful if the method gets this far without causing an exception
      Console.WriteLine("Copy completed.");
    } 

    //If the file copy fails then catch will gain control of the method
    catch (Exception exc)
    {
      Console.WriteLine(exc.Message);
    }

    Console.WriteLine("\nPress Enter to Continue:");
    Console.Read();
  }
}