Delete files from directory if filename contains a certain word

To expand on Henk’s answer, you need:

string rootFolderPath = @"C:\\SomeFolder\\AnotherFolder\\FolderCOntainingThingsToDelete";
string filesToDelete = @"*DeleteMe*.doc";   // Only delete DOC files containing "DeleteMe" in their filenames
string[] fileList = System.IO.Directory.GetFiles(rootFolderPath, filesToDelete);
foreach(string file in fileList)
{
    System.Diagnostics.Debug.WriteLine(file + "will be deleted");
//  System.IO.File.Delete(file);
}

BE VERY CAREFUL!

Note that I’ve commented out the delete command. Run it and test it carefully before you let it actually delete anything!

If you wish to recursively delete files in ALL subfolders of the root folder, add ,System.IO.SearchOption.AllDirectories); to the GetFiles call.

If you do this it is also a very good idea to refuse to run if the rootFolderPath is less than about 4 characters long (a simple protection against deleting everything in C:\ – I’ve been there and done that and it’s not fun!!!)

Leave a Comment

tech