Windows Phone Developers

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

4 comments:

  1. This only shows the basic outline.
    do u know how to copy large files. This approach crshes when applied for large files.
    Thankx

    ReplyDelete
  2. Copy Large Files using .NET

    Abhilash, Can you check if the following links help?


    http://stackoverflow.com/questions/92114/how-can-i-copy-a-large-file-on-windows-without-copyfile-or-copyfileex


    http://article.feeds4all.nl/Copy-large-files-using-freeware/17229094.aspx

    ReplyDelete
  3. Hello,

    It is working only on local machine.Can u suggest me how copy file from one system to another system.

    I have written this line of code ie
    File.Copy(@"C:\test.jpg", @"\\stellent8\\sharing\\test.jpg", true);

    In the destination stellent8 - computername;sharing - foldername of the destination it is in sharing.

    Please help me to resolve this issue soon.

    ReplyDelete

kbAlertz.com :: Visual Studio 2005

kbAlertz.com :: Visual Studio 2008

kbAlertz.com :: Visual Basic 2005