1

I am using following code to copy remote file to local. How do you detect failure in the operation, when copying large files.

Is there any better approach to detect failure, apart from handling system.io exception ?

File.Copy(remoteSrcFile, dest);

Is this the best method offered by framework to copy large files whose file size is in gigabyte range ?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Abhijeet
  • 13,562
  • 26
  • 94
  • 175

2 Answers2

4

Is there any better approach to detect failure, apart from handling system.io exception?

Many possible errors, such as an invalid file name, can be checked beforehand. If File.Copy fails, it will throw an exception. There is no other error indicator.

Is this the best method offered by framework to copy large files whose file size is in gigabyte range ?

It depends on what other features you want. For example, if you want to show progress, File.Copy will not help you, since it just wraps the FileCopy API. However, calling the Windows API FileCopyEx can provide progress. See Can I show file copy progress using FileInfo.CopyTo() in .NET? for more info.

Community
  • 1
  • 1
akton
  • 14,148
  • 3
  • 43
  • 47
  • Checking for failure before hand can be useful; but it doesn't circumvent the need to catch exceptions resulting from those. If permissions change, between when the check was made and File.Copy fails, the entire application exits--clearly not a good thing. – Peter Ritchie Sep 18 '12 at 23:27
  • @PeterRitchie There is a small window where it can happen, yes. A better example would be an invalid file name. – akton Sep 18 '12 at 23:29
  • Sure, but those particular circumstances are rare. Maybe just invalid file name or path length (not sure if they come out as the same exception)... – Peter Ritchie Sep 18 '12 at 23:31
  • @PeterRitchie I have updated the answer to exclude the more questionable cases. – akton Sep 18 '12 at 23:31
3

Copy failures are supposed to be an exceptional circumstance, so failures are modelled as exceptions.

You should wrap File.Copy calls in a try/catch to catch any exceptions you are able to explicitly accommodate.

File.Copy is the only thing "included" in the framework along with FileInfo.CopyTo. But, you can use it in different ways. Maybe spawn a thread to invoke it. You could also use basic IO to read data from one file to another to get better progress/cancellation; but, it depends on what you want to achieve.

Peter Ritchie
  • 35,463
  • 9
  • 80
  • 98