开发者

What is the most efficient way of deleting a file in regards to exception handling?

MSDN tells us that when you call "File.Delete( path );" on a file that doesn't exist an exception is generated.

Would it be more efficient to call the delete method and use a try/catch block to avoid the error or validate the existence of the file before doing the delete?

I'm inclined to think it's better to avoid the try/catch block. Why let an error occur when you know how to check for it.

Anyway, here is some sample code:

// Option 1: Just delete the file and ignore any exceptions

/// <summary>
/// Remove the files from the local server if the DeleteAfterTransfer flag has been set
/// </summary>
/// <param name="FilesToSend">a list of full file paths to be removed from the local server</param>
private void RemoveLocalFiles(List<string> LocalFiles)
{
    // Ensure there is something to process
    if (LocalFiles != null && LocalFiles.Count > 0 && m_DeleteAfterTransfer == true)
    {
        foreach (string file in LocalFiles)
        {
            try { File.Delete(file); }
            catch { }
        }
    }
}

// Option 2: Check for the existence of the file before delting
private void RemoveLocalFiles(List<string> LocalFiles )
{
    // Ensure there is something to process
    if (LocalFiles != null && LocalFiles.Count > 0 && m_DeleteAfterTransfer == true)
    {
        foreach (string file in LocalFiles)
        {
            if( File.Exists( file ) == true)
                File.Delete(file);
        }
    }
}

Some Background to what I'm trying to achieve: The code is part of an FTP wrapper class which will simplify the features of FTP functionality to only what is required and can be called by a single method call. In This case, we have a flag called "DeleteAfterTransfer" and if set to true will do the job. If the file didn't exists in the f开发者_JAVA技巧irst place, I'd expect to have had an exception before getting to this point. I think I'm answering my own question here but checking the existence of the file is less important than validating I have permissions to perform the task or any of the other potential errors.


You have essentially three options, considering that File.Delete does not throw an exception when your file isn't there:

  • Use File.Exists, which requires an extra roundtrip to the disk each time (credits to Alexandre C), plus a roundtrip to the disk for File.Delete. This is slow. But if you want to do something specific when the file doesn't exist, this is the only way.

  • Use exception handling. Considering that entering a try/catch block is relatively fast (about 4-6 m-ops, I believe), the overhead is negligible and you have the option to catch the specific exceptions, like IOException when the file is in use. This can be very beneficial, but you will not be able to act when the file does not exist, because that doesn't throw. Note: this is the easiest way to avoid race conditions, as Alexandre C explains below in more detail.

  • Use both exception handling and File.Exists. This is potentially slowest, but only marginally so and the only way to both catch exceptions and do something specific (issue a warning?) when the file doesn't exist.


A summary of my original answer, giving some more general advice on using and handling exceptions:

  • Do not use exception handling when control flow suffices, that's simply more efficient and more readable.
  • Use exceptions and exception-handling for exceptional cases only.
  • Exception handling entering try/catch is very efficient, but when an exception is thrown, this costs relatively much.
  • An exception to the above is: whenever dealing with file functions, use exception handling. The reason is that race conditions may happen and that you never know what occurs between your if-statement and your file-delete statement.
  • Never ever, and I mean: never ever use a try/catch for all exceptions (empty catch block, this is almost always a weak point in your application and needs improvement. Only catch specific exceptions. (exception: when dealing with COM exceptions not inheriting from Exception).


Another option: use Windows API DeleteFile...

[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern bool DeleteFile(string path);

This returns true if done, otherwise false. If false, you don't have the large overhead of Exceptions.


MSDN says that no exception is generated. Actually, it is better this way since you have a race condition: between calls to File.Exists and File.Delete the file could have been deleted or created by another process.

If it were to throw, you are better catching the specific exception that could have been thrown (FileNotFoundException or similar). Note that because of the race condition, exceptions are the only way to go here.

If your problem is that the directory containing the file doesn't exist, then you can do:

if (LocalFiles != null && m_DeleteAfterTransfer == true)
{
    foreach (string file in LocalFiles)
    {
        try { File.Delete(file); }
        catch (DirectoryNotFoundException e) {}
    }
}

Again, don't check for the directory existence before, because 1) it is cumbersome 2) it has the same race condition problem. Only File.Delete guarantees that the check and the delete are atomically executed.

Anyways you never want to catch every exception here since file IO methods can fail for a lot of reasons (and you surely don't want to silent a disk failure !)


There are many exceptions that can occur when trying to delete a file. Take a look here for all of them. So it's probably best to catch and deal with each of them as you see fit.


You should use File.Exists, but handle the exception anyway. In general it may be possible for the file to be deleted in between the two calls. Handling the exception still has some overhead, but checking the file for existence first reduces the throw frequency to almost-never. For the one in a million chance that the above scenario occurs, you could still ruin someone's work with an unhandled exception.


In the general case, it's indeed better to test for the exceptional case before calling the method, as exceptions should not be used for control flow.

However, we're dealing with the filesystem here, and even if you check that the file exists before deleting it, something else might remove it between your two calls. In that case, Delete() would still throw an exception even if you explicitly made sure it wouldn't.

So, in that particular case, I would be prepared to handle the exception anyway.


I think you should not only worry about efficiency, but also intention. Ask yourself questions like

  • Is it a faulty case that the list of files contains files that don't exist?
  • Do you bother about any of the other errors that can be the cause of failing to delete the file?
  • Should the process continue if errors other than "file not found" occurs?

Obviously, the Delete call can fail even if the file exists, so only adding that check will not protect your code from failure; you still need to catch exception. The question is more about what exceptions to catch and handle, and which ones should bubble upwards to the caller.


It's far better to do File.Exists first. Exceptions have a large overhead. In terms of efficiency, your definition isn't very clear, but performance and memory-wise, go for File.Exists.

See also my previous answer in this question about using Exceptions to control program flow:

Example of "using exceptions to control flow"

As below, I welcome anyone to try this themselves. People talking about spindle speed and access times for hard drives - that is massively irrelevant, because we are not timing that. The OP asked what the most performant way of achieving his task is. As you can see clear as day here, it's to use File.Exists. This is repeatable.:

Actual recorded performance results: try/catch vs File.Exists for non-existent files

Number of files (non-existent): 10,000

Source: http://pastebin.com/6KME40md

Results:

RemoveLocalFiles1 (try/catch) : 119ms

RemoveLocalFiles2 (File.Exists) : 106ms

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜