C#: File

.NET Array Collections File String Async Cast DataTable DateTime Dictionary Enum Exception For Foreach IEnumerable If IndexOf Lambda LINQ List Parse Path Process Property Regex Replace Sort Split StringBuilder Substring Switch Tuple

Warning: exclamation mark

Deleting files is not always possible. Sometimes documents are locked or unavailable. File.Delete throws an exception if this occurs. We look at exceptions related to the File.Delete method in the C# language targeting the .NET Framework.

Tip:Use File.Delete to delete files on the computer. This method will throw an exception in some cases.



This program demonstrates one way to use the File.Delete method. We look at how you can catch the IOExceptions thrown by the File.Delete method and execute commands in this case. The type we want to detect is the System.IO.IOException.


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.

C# program that catches IOException

using System.IO;

class Program
    static void Main()
	// 1.
	// Call Delete wrapper method.

    /// <summary>
    /// Wrap the Delete method with an exception handler.
    /// </summary>
    static bool TryToDelete(string f)
	    // A.
	    // Try to delete the file.
	    return true;
	catch (IOException)
	    // B.
	    // We could not delete the file.
	    return false;

    The file is deleted, or nothing happens.

In part A, we try to delete a file. If the file is properly deleted or isn't there at all, then the method succeeds and returns true. In part B, we handle errors. We return false if something goes wrong and we catch an IOException.

Also:It is recommended that you always catch the most specific exception type possible.



Speech bubble

The File.Delete method will permanently delete a file, bypassing the recycle bin. You must be careful with exceptions—File.Delete does not throw an exception when a file doesn't exist. When exceptions are thrown, the file is locked.

File.Delete:Deletes the specified file. An exception is not thrown if the specified file does not exist.


We dealt with exceptions raised when trying to use the File.Delete method in the C# language. Never make any assumptions about the filesystem. Instead always check for errors and unexpected conditions.

Caution:File handling results in exceptions being thrown even in normal situations.