Summary: in this tutorial, you’ll learn how to use delete an existing file using the C#
static method.File.Delete
()
Introduction to the C# File.Delete() method
The
static method allows you to delete a file specified by a path:File.Delete
()
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
method. We use the
()File.Delete
method to combine the directory and filename and pass it to the Path.Combine
()
method
()File.Delete
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
to delete all text files from the File.Delete
()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
method:Directory.GetFiles
()
var filenames = Directory.GetFiles(dir,"*.txt");
Code language: C# (cs)
Third, iterate through the files and delete each of them using the
method. Also, write a message to the console to indicate the file to be deleted:File.Delete
()
foreach (var filename in filenames)
{
WriteLine($"Deleting file {filename}");
File.Delete(filename);
}
Code language: C# (cs)
Summary
- Use the
method to delete a file.File.Delete
()