Windows Phone Developers

Showing posts with label Copy files in C#. Show all posts
Showing posts with label Copy files in C#. Show all posts

Saturday, November 1, 2008

Copy Files using C# / Copy files using .NET

File.Copy method can be used for copying the files. The function with two arguments copies an existing file to a new file; overwriting a file of the same name is not allowed. However, overwriting can be done by setting a flag in the third parameter of the overloaded function.

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




FileCopy IOException
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon