How to know that File.Copy succeeded?
Asked Answered
U

5

18

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.

Underpinnings answered 29/10, 2011 at 9:14 Comment(3)
My guess,, if it didnt throw a exception (IOException for example)Turd
You could do it with a Boolean.Incudes
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.Lamoureux
I
24

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.
Incudes answered 29/10, 2011 at 9:18 Comment(1)
Whilst it's not actually necessary, you can also use File.Exists to double check.Ecosphere
T
12

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.

Trug answered 29/10, 2011 at 9:37 Comment(1)
I have a problem. File.Copy throws no exception however it does not copy the file. Ideas?Furness
W
6

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

Wentzel answered 29/10, 2011 at 9:17 Comment(5)
But I need to do it programatically. Is it possible to check that no exception happenedUnderpinnings
@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.Wentzel
@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.Liverpudlian
@JonSkeet: I know how to use SEH very well, but i am asking about how to put "no exception" as a condition.Underpinnings
@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.)Liverpudlian
P
2

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.");
        }
    }
}
Plebeian answered 29/10, 2011 at 9:51 Comment(0)
A
1

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;

}
Adrienneadrift answered 29/10, 2011 at 10:3 Comment(1)
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?Filmdom

© 2022 - 2024 — McMap. All rights reserved.