Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 first 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.

like image 808
TeamWild Avatar asked Aug 12 '11 08:08

TeamWild


People also ask

What is a good way to handle exceptions when trying to write a file in Python?

In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.

How do I delete an exception?

To catch and delete exceptionsUse the try keyword to set up a try block. Execute any program statements that might throw an exception within a try block. Use the catch keyword to set up a catch block. Place exception-handling code in a catch block.

Which method is used to delete a directory?

The rm command removes complete directories, including subdirectories and files. The rmdir command removes empty directories.


2 Answers

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).
like image 150
Abel Avatar answered Sep 21 '22 01:09

Abel


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.

like image 41
robertpnl Avatar answered Sep 22 '22 01:09

robertpnl