Home
C#
File.Delete
Updated Dec 11, 2021
Dot Net Perls
File.Delete. Deleting files can sometimes fail—a document may be locked or unavailable. File.Delete throws an exception if this occurs.
C# method info. We see exceptions related to File.Delete, and describe a way to handle those exceptions. The exact exception type is System.IO.IOException.
File
Example program. To begin, this program shows the usage of the File.Delete static method. We can catch the IOExceptions thrown by File.Delete and execute special logic.
IOException
static
Note The metadata says that this indicates that "The specified file is in use."
Tip We can wrap the Delete call in another method that handles some of the errors.
Detail We invoke File.Delete here. If the file is properly deleted or is not present, then the method succeeds and returns true.
Detail Here we handle errors. We return false if something goes wrong and we catch an IOException.
catch
Exception
using System.IO;

class Program
{
    static void Main()
    {
        // Call Delete wrapper method.
        TryToDelete("Word.doc");
    }

    /// <summary>
    /// Wrap the Delete method with an exception handler.
    /// </summary>
    static bool TryToDelete(string f)
    {
        try
        {
            // Try to delete the file.
            File.Delete(f);
            return true;
        }
        catch (IOException)
        {
            // We could not delete the file.
            return false;
        }
    }
}
The file is deleted, or nothing happens.
Discussion. We must be careful with exceptions—File.Delete does not throw an exception when a file does not exist. When exceptions are thrown, the file is locked.
Detail Deletes the specified file. An exception is not thrown if the specified file does not exist.
Summary. We dealt with exceptions raised when trying to use the File.Delete method. Never make any assumptions about the file system—always check for errors and unexpected conditions.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 11, 2021 (edit).
Home
Changes
© 2007-2025 Sam Allen