Delete a file

suggest change

Deleting a file, if you have the required permissions, is as simple as:

File.Delete(path);

However many things may go wrong:

File.Delete does not throw if the file is already absent. A check like the following is still not atomic: the file can disappear between Exists and Delete:

if (File.Exists(path))
    File.Delete(path);

The right way to handle a failed I/O operation is exception handling (assuming another course of action is possible when the operation fails):

if (File.Exists(path))
{
    try
    {
        File.Delete(path);
    }
    catch (IOException exception)
    {
        if (!File.Exists(path))
            return; // Someone else deleted this file

        // Something went wrong...
    }
    catch (UnauthorizedAccessException exception)
    {
        // I do not have required permissions
    }
}

Some of these I/O errors are transitory (a file in use, for example). If a network connection is involved, it may recover without any action from our side. It is then common to retry an I/O operation a few times, with a short delay between attempts:

public static void Delete(string path)
{
    if (!File.Exists(path))
        return;

    for (int i=1; ; ++i)
    {
        try
        {
            File.Delete(path);
            return;
        }
        catch (IOException e)
        {
            if (!File.Exists(path))
                return;

            if (i == NumberOfAttempts)
                throw;

            Thread.Sleep(DelayBetweenEachAttempt);
        }

        // You may handle UnauthorizedAccessException, but that
        // probably will not be fixed in a few seconds.
    }
}

private const int NumberOfAttempts = 3;
private const int DelayBetweenEachAttempt = 1000; // ms

On Windows, if another handle has the file open with FileShare.Delete, File.Delete can succeed while the file remains until that handle is closed.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents