What is the fastest way of deleting files in a directory? (Except specific file extension)

GeorgeBoy picture GeorgeBoy · Feb 13, 2011 · Viewed 13.1k times · Source

I have seen questions like What is the best way to empty a directory?

But I need to know,

what is the fastest way of deleting all the files found within the directory, except any .zip files found.

Smells like linq here... or what?

By saying fastest way, I mean the Fastest execution time.

Answer

ceciliaSHARP picture ceciliaSHARP · Feb 13, 2011

If you are using .NET 4 you can benifit the smart way .NET now parallizing your functions. This code is the fasted way to do it. This scales with your numbers of cores on the processor too.

DirectoryInfo di = new DirectoryInfo(yourDir);
var files = di.GetFiles();

files.AsParallel().Where(f => f.Extension != ".zip").ForAll((f) => f.Delete());