Which method of deleting files has the best performance?
Just to note the root directory must be still there, so either I can do:
var photo_files = Directory.EnumerateFiles(item_path, "*.jpg", SearchOption.TopDirectoryOnly);
foreach (var photo in photo_files)
{
File.Delete(photo);
}
Or delete the whole directory and then create it again.
How much performance difference would there be for 10000 or even 100000 files?
P.S. Just to clarify, .NET has no function to delete all files in a folder at once and leaving the directory.
When you delete a directory it is a single write to the drive's master file table, whereas if you delete each file then there is a write operation per file. Thus it is more efficient to delete the directory and recreate it.
Following the exchange with @Mr Disappointment I would offer the following amendment to my answer:
If you need to do this "a lot" then you might build yourself an extension method that looks like this:
public static class IOExtension
{
public static void PurgeDirectory(this DirectoryInfo d)
{
string path = d.FullName;
Directory.Delete(d.FullName,true);//Delete with recursion
Directory.CreateDirectory(path);
}
}
so that you can just invoke this on the DirectoryInfo class like...
Directory Info di = new DirectoryInfo(path);
di.PurgeDirectory();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With