How to know that File.Copy succeeded?

▼魔方 西西 提交于 2019-11-29 09:15:22

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.

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.

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

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.");
        }
    }
}

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;

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!