How to know that File.Copy succeeded?

39,519

Solution 1

If the operation doesn't throw any exception, it means that it was successful. The list of the possible exceptions is available here :

UnauthorizedAccessException

  • The caller does not have the required permission.

ArgumentException

  • sourceFileName or destFileName is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.

  • -or-

  • sourceFileName or destFileName specifies a directory.

ArgumentNullException

  • sourceFileName or destFileName is null.

PathTooLongException

  • The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.

DirectoryNotFoundException

  • The path specified in sourceFileName or destFileName is invalid (for example, it is on an unmapped drive).

FileNotFoundException

  • sourceFileName was not found.

IOException

  • destFileName exists.

  • -or-

  • An I/O error has occurred.

NotSupportedException

  • sourceFileName or destFileName is in an invalid format.

Solution 2

Errors

If the method doesn't throw an exception, no error occurred. The method was able to perform the job it promised it would do, so it will get out of the way, and won't try to return some sort of status code. You won't need to check a status code because you will know that it has succeeded.

If the method fails the copy operation, an exception will be thrown. In this case the method wasn't able to perform the job it promised it would do, which means something weird (exceptional) happened, so an exception gets thrown. Since an exception is thrown, you are forced to deal with it, or your program blows up. So there is no point in checking for a status code. You couldn't write any code that would be able to read that status code anyhow, since the status checking code would never be reached. Code flow would go to the catch block, or to program termination.

These concepts are the basis of error handling using exceptions.

How to handle exceptions

Unless you need to, and have some reasonable way to recover from the exception, then don't handle them. Let your program blow up. This will make it much easier to find bugs in your code out in the wild, since an unhandled exception will produce a stack trace, which will tell you exactly which part of your program blew up, and how the code got to that point.

If you have a reasonable way to recover (e.g. simply display an error message to the user and retry the operation, or let them input a different parameter), then you can write a try/catch block. Write your code that could throw an exception in the try block, and write your recovery code in the catch block.

try
{
    var file = File.Open(filename);
    // Todo: Work with open file here
}
catch(FileNotFoundException e)
{
    MessageBox.Show("Failed to open file - " + e.ToString());
    // Todo: Additional recovery here,
    // like telling the calling code to re-open the file selection dialog
}

Note that you should never catch the base Exception type, and instead should catch the specific derived exception types that you can handle (e.g. FileNotFoundException). This makes sense because you probably can't write code that will successfully recover from an OutOfMemoryException, and that exception could get thrown at any point in your code. If you catch Exception, then you are writing code that tries to handle anything, not just the exceptions you are interested in.

Completion

File.Copy is a synchronous operation. So once the method has completed, then the actual copy has completed.

This means that you can write a line of code immediately after the copy line. And that code can expect the file to be there, for it to be fully copied, and for it to be accessible.

Solution 3

If the method doesn't throw an exception it means that it has succeeded.

Solution 4

if there is no exception that it means that the file is success fully copied ...

using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";
        string path2 = path + "temp";

        try 
        {
            // Create the file and clean up handles.
            using (FileStream fs = File.Create(path)) {}

            // Ensure that the target does not exist.
            File.Delete(path2);

            // Copy the file.
            File.Copy(path, path2);
            Console.WriteLine("{0} copied to {1}", path, path2);

            // Try to copy the same file again, which should succeed.
            File.Copy(path, path2, true);
            Console.WriteLine("The second Copy operation succeeded, which was expected.");
        } 

        catch 
        {
            Console.WriteLine("Double copy is not allowed, which was not expected.");
        }
    }
}

Solution 5

Though I dont know what situation you are into , but i have something similar situation where I have to Copy files and needed to know if it succeeded, As i could'nt find anything useful in .NET API my only option was to keep trying until it succeeds (try it no. of times) eg in following code I have to give up after 5 tries

private bool CopyDone()
{
  bool done = false;
  int i = 0;
  string source = "SourceFile";
  while (i < 5)
  {
    try
    {

      System.IO.File.Copy(source, target, true);
      i = 5;
      done = true;
    }
    catch (Exception exp)
    {
      Trace.WriteLine("File trouble " + exp.Message);
      System.Threading.Thread.Sleep(1000);
      i++;
    }

   }

  /* if(!done)
   {
      Trace.WriteLine("Failed to copy file "+source );
   }*/
  return done;

}
Share:
39,519

Related videos on Youtube

Aan
Author by

Aan

I need to learn more &amp; more.

Updated on July 09, 2022

Comments

  • Aan
    Aan almost 2 years

    The static method File.Copy(String, String) doesn't return a value. How can I know programatically if that function succeeded or not ? If there is no thrown exception, File.Copy goes well. But I am asking about how to put "no exception" as a condition.

    Something like this:

    if(no exception happened){
    
    //my code goes here
    
    }
    

    Edit: I have solved the problem using a simple counter as following:

    int i=0;
    try{
        File.Copy();
    }
    catch(e1){
        i++;
    }
    catch(e2){
        i++;
    }
    
    if(i==0){
        //my code goes here
    }
    

    Thanks for all contributors. I will go through your answers to choose the best.

    • SynerCoder
      SynerCoder over 12 years
      My guess,, if it didnt throw a exception (IOException for example)
    • shraysalvi
      shraysalvi over 12 years
      You could do it with a Boolean.
    • user1703401
      user1703401 over 12 years
      You'll have to learn to live with uncertainty when dealing with the file system. When somebody trips over the power cord right after File.Copy() returns without throwing an exception then you still don't have a copy. Don't sweat the small stuff and get rid of that counting code.
  • Aan
    Aan over 12 years
    But I need to do it programatically. Is it possible to check that no exception happened
  • Darin Dimitrov
    Darin Dimitrov over 12 years
    @Adban, of course, if an exception is thrown there are 2 possibilities: either you handle it (using try/catch) or you leave it propagate in which case your program will crash.
  • Jon Skeet
    Jon Skeet over 12 years
    @Adban: How familiar are you with C# and exceptions? If you're unsure how to see whether an exception occurred or not, it may be worth hitting the books a bit more - don't try to just get past this one File.Copy call - learn more about exceptions in general.
  • Aan
    Aan over 12 years
    @JonSkeet: I know how to use SEH very well, but i am asking about how to put "no exception" as a condition.
  • Jon Skeet
    Jon Skeet over 12 years
    @Adban: Um, you put the method call within a try/catch block - if you don't hit the catch block, it didn't throw an exception... (For example, you might have return true; just after the File.Copy call inside the try block, and return false; in the catch block, if you just need a method which will return whether or not it succeeded.)
  • Polynomial
    Polynomial over 12 years
    Whilst it's not actually necessary, you can also use File.Exists to double check.
  • Aan
    Aan over 12 years
    Thanks, your answer was very useful. SSamra answer gives direct solution.
  • NoChance
    NoChance over 9 years
    I don't think this is the correct approach, and hence this should not be the accepted answer. The operation is either complete or not. Why do you think the result at the n-th time is better than the result at the first time?
  • rollsch
    rollsch almost 7 years
    I have a problem. File.Copy throws no exception however it does not copy the file. Ideas?