C# – How to delete a file

You can use File.Delete() (in System.IO) to delete a file by specifying its relative or absolute path. Here’s an example:

using System.IO;

//Delete from one level up
File.Delete("../a.txt");

//Delete from current directory
File.Delete("b.txt");

//Delete using full path
File.Delete("D:/Temp/c.txt");
Code language: C# (cs)

Note: Unlike other methods in the File API, there’s no async version of File.Delete().

If the specified file exists and the permissions are right, then File.Delete() deletes the file as expected. If there’s a problem, it throws an exception.

File.Delete() deletes a single file. You can use this in a loop to delete multiple files in a directory (without deleting the directory itself).

I’ll discuss a few problems to watch out for when deleting a file.

Checking if the file exists before deleting

If the file doesn’t exist, File.Delete() does nothing. It doesn’t throw an exception. Therefore, you don’t need to check if it exists before attempting to delete it.

However, there’s a catch. If the directory in the path doesn’t exist, then it throws an exception:

System.IO.DirectoryNotFoundException: Could not find a part of the path ‘C:\Temp2\c.txt’.

Either the directory no longer exists because it was deleted intentionally -or- the path is wrong and should be fixed.

If you know the path is right and you expect the directory to be missing for valid reasons, then you can guard against this exception by using File.Exists():

using System.IO;

var path = "C:/Temp2/c.txt";

if (File.Exists(path))
{
    File.Delete(path);
}
Code language: C# (cs)

Remember that File.Delete() does nothing if the file doesn’t exist, so using File.Exists() is only necessary if you want to guard against DirectoryNotFoundException.

File.Exists() returns false if either the file or directory doesn’t exist. If you want to know specifically if the directory doesn’t exist, use Directory.Exists() (without the file name):

using System.IO;

var path = "C:/Temp2/c.txt";

if (Directory.Exists(Path.GetDirectoryName(path)))
{
    File.Delete(path);
}
else
{
    Console.WriteLine("Directory doesn't exist");
}
Code language: C# (cs)

Note: Of course, you can always catch DirectoryNotFoundException if want to use try/catch blocks instead.

Exceptions if the path is invalid

When you call File.Delete(), you need to pass it a valid path, otherwise you’ll run into exceptions.

  • It can’t be null/empty.
  • The directory has to exist (as mentioned in the section above).
  • It has to be a file path, not a directory path.

If you pass in a directory path, you get a misleading exception that looks like a permissions error:

System.UnauthorizedAccessException: Access to the path ‘C:\Temp\Test\’ is denied.

You can’t use File.Delete() to delete a directory. Use Directory.Delete() for that.

Leave a Comment