C# Delete File

Summary: in this tutorial, you’ll learn how to use delete an existing file using the C# File.Delete() static method.

Introduction to the C# File.Delete() method

The File.Delete() static method allows you to delete a file specified by a path:

public static void Delete (string path);Code language: C# (cs)

In this syntax, the path species is the name of the file to be deleted.

The Delete() method raises an ArgumentException if the path is a zero-length string and ArgumentNullException if the path is null.

If the file is in use, the Delete() method raises an IOException.

Note that if the file does not exist, the File.Delete() method will NOT raise any exception.

C# File.Delete() example

The following program demonstrates how to delete the readme.txt file from the C:\tmp directory:

using static System.Console;

string directory = @"C:\temp";
string filename = @"readme1.txt";

try
{
    File.Delete(Path.Combine(directory, filename));
}
catch (IOException ex)
{
    WriteLine(ex.Message);
}Code language: C# (cs)

How it works.

First, define two variables directory and filename to store the directory and name of the file to be deleted:

string directory = @"C:\temp";
string filename = @"readme1.txt";Code language: C# (cs)

Second, delete the file using the File.Delete() method. We use the Path.Combine() method to combine the directory and filename and pass it to the File.Delete() method

Also, we use the try...catch block to handle any potential errors that may occur when deleting the file:

try
{
    File.Delete(Path.Combine(directory, filename));
}
catch (IOException ex)
{
    WriteLine(ex.Message);
}Code language: C# (cs)

If an error occurs, the program writes the error message to the console using the WriteLine() method.

Deleting all files in a directory

The following example demonstrates how to use the File.Delete() to delete all text files from the C:\temp directory:

using static System.Console;

string dir = @"C:\temp";

var filenames = Directory.GetFiles(dir,"*.txt");
foreach (var filename in filenames)
{
    WriteLine($"Deleting file {filename}");
    File.Delete(filename);
}Code language: C# (cs)

How it works.

First, define a variable called dir that stores the path to the directory:

string dir = @"C:\temp";Code language: C# (cs)

Second, get all text files from the dir directory using the Directory.GetFiles() method:

var filenames = Directory.GetFiles(dir,"*.txt");Code language: C# (cs)

Third, iterate through the files and delete each of them using the File.Delete() method. Also, write a message to the console to indicate the file to be deleted:

foreach (var filename in filenames)
{
    WriteLine($"Deleting file {filename}");
    File.Delete(filename);
}Code language: C# (cs)

Summary

  • Use the File.Delete() method to delete a file.
Was this tutorial helpful ?