private static bool CopyFiles(string sSource, string sDestn)
{
try
{
if (File.Exists(sSource) == true)
{
File.Copy(sSource, sDestn);
return true;
}
else
{
Console.WriteLine("Specifed file does not exist");
return false;
}
}
catch (FileNotFoundException exFile)
{
Console.WriteLine("File Not Found " + exFile.Message);
return false;
}
catch (DirectoryNotFoundException exDir)
{
Console.WriteLine("Directory Not Found " + exDir.Message);
return false;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
The function can be invoked by
CopyFiles (@"C:\Temp\DotNetDud\Sample.txt", @"C:\Temp\DotNetDud\CSharpSample\Sample_Bkup.txt");
Overwriting files in C#
The above function will throw IOException if the destination file exists. To overcome this you can use the following
File.Copy(sSource, sDestn, true );