Home »
.Net »
C# Programs
C# - How to Delete a File?
Learn, how to delete a text file using C# program?
Submitted by IncludeHelp, on October 29, 2017 [Last updated : March 26, 2023]
Given a file, and we have to delete it using C# program.
Deleting a file
To delete a file in C#, we use File.Delete() method. The delete() method deletes the file from the given path. Where the path defines the name of the file to be deleted. This method may raise an ArgumentException if the path is a zero-length string and an ArgumentNullException if the path is null. If the file to be deleted is in use by another application, it raises an IOException.
File.Delete()
This is a method of "File" class, it is used to delete the given file.
Syntax
void File.Delete(path);
Parameter(s)
path - Filename with its location.
C# program to delete a file
using System;
using System.IO;
namespace ConsoleApplication1 {
class Program {
static void Main() {
//method to delete file
File.Delete("123.TXT");
//confirmation message
Console.WriteLine("File deleted successfully");
}
}
}
Output
File deleted successfully
Explanation
In the above program, we need to remember, when we use "File" class, System.IO namespace must be included in the program. An exception is not thrown if the specified file does not exist.
C# File Handling Programs »