90

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?

Ry-
  • 218,210
  • 55
  • 464
  • 476
prongs
  • 9,422
  • 21
  • 67
  • 105

4 Answers4

151

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.)

Ry-
  • 218,210
  • 55
  • 464
  • 476
73

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.

miroxlav
  • 11,796
  • 5
  • 58
  • 99
Brian Cryer
  • 2,126
  • 18
  • 18
  • 4
    Note that `DirectoryInfo` has `EnumerateFiles()` as well. – TrueWill Oct 27 '15 at 17:29
  • 10
    In case anyone is wondering why this answer is so similar to the accepted answer, it is because the accepted answer has been rewritten in light of this one. Which is a shame because using `DirectoryInfo.GetFiles()` (which was the original answer) is the only way to do it for earlier versions of .NET. – Brian Cryer May 09 '17 at 10:58
  • 2
    This answer, Directory.EnumerateFiles(), is still faster than then accepted one as it returns an IEnumerable of strings, rather than FileInfo classes where all the other properties need to be populated too. If want to do something else with the file information before or after deleting it, use DirectorInfo, but if you are just deleting use Directory. In a large directory it will be a lot faster. – Deano Jul 06 '19 at 01:07
8

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.

keyboardP
  • 68,824
  • 13
  • 156
  • 205
4

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);
zumalifeguard
  • 8,648
  • 5
  • 43
  • 56
s1cart3r
  • 334
  • 1
  • 4
  • 9