C# File.Delete

Remove a file with the File.Delete method from the System.IO namespace.
File.Delete. Deleting files can sometimes fail—a document may be locked or unavailable. File.Delete throws an exception if this occurs. We see exceptions related to File.Delete, and describe a way to handle those exceptions.File
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. The exact exception type is System.IO.IOException.IOExceptionStatic

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.

Part A: We invoke File.Delete here. If the file is properly deleted or is not present, then the method succeeds and returns true.

Part B: Here we handle errors. We return false if something goes wrong and we catch an IOException.

CatchExceptionBool Method
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.
Discussion. 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 does not 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—always check for errors and unexpected conditions.

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

Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to