C# File.Delete

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.

Example

Program

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.

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.
	TryToDelete("Word.doc");
    }

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

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

Exception

Discussion

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.

Summary

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.


C#: File