Deleting multiple files with wildcard

C#Windows

C# Problem Overview


You know that in linux it's easy but I can't just understand how to do it in C# on Windows. I want to delete all files matching the wildcard f*.txt. How do I go about going that?

C# Solutions


Solution 1 - C#

You can use the DirectoryInfo.EnumerateFiles function:

var dir = new DirectoryInfo(directoryPath);

foreach (var file in dir.EnumerateFiles("f*.txt")) {
    file.Delete();
}

(Of course, you'll probably want to add error handling.)

Solution 2 - C#

I know this has already been answered and with a good answer, but there is an alternative in .NET 4.0 and higher. Use Directory.EnumerateFiles(), thus:

foreach (string f in Directory.EnumerateFiles(myDirectory,"f*.txt"))
{
    File.Delete(f);
}

The disadvantage of DirectoryInfo.GetFiles() is that it returns a list of files - which 99.9% of the time is great. The disadvantage is if the folder contains tens of thousands of files (which is rare) then it becomes very slow and enumerating through the matching files is much faster.

Solution 3 - C#

You can use the Directory.GetFiles method with the wildcard overload. This will return all the filenames that match your pattern. You can then delete these files.

Solution 4 - C#

I appreciate this thread is a little old now, but if you want to use linq then

Directory.GetFiles("f:\\TestData", "*.zip", SearchOption.TopDirectoryOnly).ToList().ForEach(File.Delete);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionprongsView Question on Stackoverflow
Solution 1 - C#Ry-View Answer on Stackoverflow
Solution 2 - C#Brian CryerView Answer on Stackoverflow
Solution 3 - C#keyboardPView Answer on Stackoverflow
Solution 4 - C#s1cart3rView Answer on Stackoverflow