Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete file vs directory + recreate performance

Which method of deleting files has the best performance?

  • Deleting per file, or
  • Deleting whole directory with files at once and recreating the directory

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.

like image 894
Programista Avatar asked Apr 13 '11 14:04

Programista


1 Answers

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();
like image 169
Cos Callis Avatar answered Sep 17 '22 20:09

Cos Callis