c# Delete Files

The code below is c# code. click here for the Windows PowerShell version. It will delete any files matching the search criteria in the given location. There are many ways of doing this, so please bear in mind that this is not the only solution available.

Add the following line to the top of your code:

using System.IO;

Now the following code will delete every file in a given location where the file extension matches the search pattern of “.tmp”.

foreach(string fl in Directory.GetFiles(@”target directory here”,”.tmp”, SearchOption.AllDirectories))
{
File.Delete(fl);
}

You can customise this to your needs, changing “.tmp” to the file extension you want to delete. Changing the SearchOption.AllDirectories to SearchOption.TopDirectoryOnly will only search the target folder and not the subfolders. You could even add the target directory into a variable and call it using the below example:

String TargetDir = @”Target Directory here”;
foreach(string fl in Directory.GetFiles(TargetDir,”.tmp”, SearchOption.AllDirectories))
{
File.Delete(fl);
}

You could also add the SearchPattern (“.tmp”) into another variable and call that too. See below:

String TargetDir = @”Target Directory here”;
String FileExt = “.tmp”;
foreach(string fl in Directory.GetFiles(TargetDir,FileExt, SearchOption.AllDirectories))
{
File.Delete(fl);
}

One way of deleting multiple files with different types of file extensions is below. This can also be amended to go through subfolders by changing the SearchOption below to SearchOption.AllDirectories:

string TargetDir = @”target directory here”;
var ChosenFileExts = System.IO.Directory
.GetFiles(TargetDir, “*.*”, SearchOption.TopDirectoryOnly) // file.ToLower().EndsWith(“doc”) || file.ToLower().EndsWith(“txt”) || file.ToLower().EndsWith(“exe”))
.ToList();

foreach (string file in ChosenFileExts)
{
File.Delete(file);
}

Use all code at your own risk. while this has been tested in my environment, it should be tested on a temporary directory prior to running properly.

Leave a Reply