To delete a single file in C#, use File.Delete, and pass in a string of the name of the file.
Delete a single file
If you have the name of a file in a string, you can either call File.Delete (from the System.IO namespace) and pass in the string name, or you can create a FileInfo object (using the string) and call Delete on the FileInfo object.
NOTE: This does not allow wildcards in the file name.
using System.IO; void DeleteSingleFile() { // Does not allow wildcards in file name File.Delete("e:\\test\\test.txt"); // Uses @, to prevent needing to escape back-slashes FileInfo fileToDelete = new FileInfo(@"e:\test\test.txt"); fileToDelete.Delete(); }
Delete multiple files (with wildcard)
If you want to delete multiple files, using a wildcard, you can create a DirectoryInfo object for the directory. Then, call EnumerateFiles on it, passing in the search pattern, to get FileInfo objects for each file that matches the search pattern.
Then call Delete on each FileInfo object to delete the file.
using System.IO; void DeleteMultipleFilesWithWildcard() { DirectoryInfo dirInfo = new DirectoryInfo(@"e:\test"); // Deletes matching files in the selected directory foreach (FileInfo file in dirInfo.EnumerateFiles("*.txt")) { file.Delete(); } // SearchOption deletes matching files in sub-directories foreach (FileInfo file in dirInfo.EnumerateFiles("*.txt", SearchOption.AllDirectories)) { file.Delete(); } }
You can also pass in a second parameter to the EnumerateFiles function – either SearchOptions or EnumerationOptions.
The SearchOption lets you state if you only want matching files in the current directory of the DirectoryInfo object, or if you want to include files in its subdirectories.
The EnumerationOptions gives you more parameters, letting you do things like only include files if the case (upper/lower case letters of the file name) match, skip hidden files, limit how many levels deep of subdirectories to include, etc.
Delete a directory, along with all the files in it
If you want to delete a directory, along with the files in it, create a DirectoryInfo object for the directory and call Delete on it, passing in “true” for the optional parameter. The “true” tells the Delete to also delete the files in the directory.
If the directory has files in it, and you do not pass in a “true”, the Delete function will throw an exception, saying the directory is not empty.
using System.IO; void DeleteDirectoryAndFiles() { // Remove a directory, its sub-directories, and files DirectoryInfo dirInfo = new DirectoryInfo(@"e:\test"); dirInfo.Delete(true); }