Delete a File in C# Using File.Delete()
To delete a file in C#, call the System.IO.File.Delete(path) method with the path of the file. The method permanently removes the specified file rather than moving it to the Recycle Bin.
The following statement deletes the file represented by path:
File.Delete(path);
Include the System.IO namespace before using the File class. The application must also have permission to delete the file.
Example 1 – Delete a File with File.Delete()
In the following example, we shall delete a file with the path D:\sample.txt.
Program.cs
using System;
using System.IO;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
String path = @"D:\sample.txt";
File.Delete(path);
Console.WriteLine("Deleted file successfully.");
}
}
}
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
Deleted file successfully.
The success message is printed after File.Delete() returns. However, this message alone does not prove that a file existed before the call because File.Delete() also returns normally when the target file does not exist.
Check Whether the File Exists Before Deleting It
Use File.Exists() when the program needs to distinguish between a deleted file and a file that was already missing.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = @"D:\sample.txt";
if (File.Exists(path))
{
File.Delete(path);
Console.WriteLine("The file was deleted.");
}
else
{
Console.WriteLine("The file does not exist.");
}
}
}
Another process can still change or lock the file after File.Exists() is checked. Therefore, applications should handle exceptions raised by the actual delete operation.
What Happens When the File Does Not Exist?
If the specified file does not exist, File.Delete() does not throw a FileNotFoundException. The method completes without deleting anything. The containing directory must still be valid and accessible.
Example 2 – Delete File with Path specified as null
If you specify path as null, System.ArgumentNullException is thrown by File.Delete() function.
Program.cs
using System;
using System.IO;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
String path = null;
File.Delete(path);
Console.WriteLine("Deleted file successfully.");
}
}
}
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
Unhandled Exception: System.ArgumentNullException: Value cannot be null.
Parameter name: path
at System.IO.File.Delete(String path)
at CSharpExamples.Program.Main(String[] args) in D:\workspace\csharp\HelloWorld\Program.cs:line 8
Validate paths received from user input, configuration files, or method parameters before attempting deletion.
Example 3 – Delete File – Path Containing Invalid Path Characters
The path should not contain invalid path characters. Invalid path characters’ numeric range is [0, 31] and 124. If path contains any of these invalid path characters, System.IO.IOException is thrown by File.Delete() function.
Program.cs
using System;
using System.IO;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
String path = "D:/sample1|.txt";
File.Delete(path);
Console.WriteLine("Deleted file successfully.");
}
}
}
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
Unhandled Exception: System.IO.IOException: The filename, directory name, or volume label syntax is incorrect : 'D:\sample1|.txt'
at System.IO.FileSystem.DeleteFile(String fullPath)
at System.IO.File.Delete(String path)
at CSharpExamples.Program.Main(String[] args) in D:\workspace\csharp\HelloWorld\Program.cs:line 8
Path validation rules depend on the operating system and the .NET runtime. Instead of relying only on a fixed character list, build paths with methods such as Path.Combine() and handle exceptions from File.Delete().
Handle File Deletion Errors in C#
A file may exist but still cannot be deleted. Common causes include insufficient permissions, a read-only attribute, an invalid path, or another process using the file. The following example handles several common exceptions.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = @"D:\sample.txt";
try
{
File.Delete(path);
Console.WriteLine("Delete operation completed.");
}
catch (ArgumentNullException)
{
Console.WriteLine("The file path is null.");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Permission was denied or the path refers to a directory.");
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("A directory in the specified path was not found.");
}
catch (IOException ex)
{
Console.WriteLine($"The file could not be deleted: {ex.Message}");
}
catch (NotSupportedException)
{
Console.WriteLine("The file path uses an unsupported format.");
}
}
}
Catch only the exceptions that the application can handle meaningfully. Logging the exception message can help diagnose permission, path, and file-locking problems.
Delete a Read-Only File in C#
On systems where a read-only attribute prevents deletion, remove that attribute before calling File.Delete(). Only do this when the application is intentionally allowed to modify the file.
using System.IO;
string path = @"D:\sample.txt";
if (File.Exists(path))
{
FileAttributes attributes = File.GetAttributes(path);
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
File.SetAttributes(path, attributes & ~FileAttributes.ReadOnly);
}
File.Delete(path);
}
File.Delete() Behavior and Common Exceptions
| Condition | Typical result |
|---|---|
| The file exists and is accessible | The file is deleted. |
| The file does not exist | The method normally returns without throwing an exception. |
The path is null | ArgumentNullException is thrown. |
| The application lacks permission | UnauthorizedAccessException may be thrown. |
| A directory in the path does not exist | DirectoryNotFoundException may be thrown. |
| The file is in use or the path is invalid | IOException may be thrown. |
| The path format is unsupported | NotSupportedException may be thrown. |
Frequently Asked Questions About Deleting Files in C#
Does File.Delete() throw an exception when the file is missing?
No. If the specified file does not exist, File.Delete() normally completes without throwing a file-not-found exception.
Does File.Delete() move a file to the Recycle Bin?
No. File.Delete() permanently deletes the file through the file system. It does not provide an undo operation or move the file to the Recycle Bin.
Can File.Delete() delete a directory?
No. Use Directory.Delete() to delete a directory. Passing a directory path to File.Delete() can result in an exception.
Why does C# report that a file is being used by another process?
The file may still be open in your application or locked by another process. Dispose streams, readers, and writers before calling File.Delete(). A using statement helps close disposable file resources correctly.
C# File Deletion Review Checklist
- Confirm that the path identifies a file rather than a directory.
- Use
Path.Combine()when constructing paths from separate directory and file names. - Decide whether a missing file should be treated as success or reported to the user.
- Close any streams or file handles before deleting the file.
- Handle permission, invalid-path, missing-directory, and file-lock exceptions where appropriate.
- Avoid printing a success message unless it accurately represents the intended application behavior.
Summary of File.Delete() in C#
In this C# Tutorial, we learned how to delete a file using File.Delete(), check whether a file exists, handle common deletion errors, and remove a read-only attribute when necessary. Remember that File.Delete() permanently removes a file and normally does not throw an exception when the target file is already missing.
TutorialKart.com