title: Delete a large number (>100K) of files with c# whilst maintaining performance in a web application?
body: <p>I am trying to remove a <strong>large</strong> number of files from a location (by large I mean over 100000), whereby the action is initated from a web page. Obviously I could just use </p>
  
  <pre><code>string[] files = System.IO.Directory.GetFiles("path with files to delete");
  foreach (var file in files) {
      IO.File.Delete(file);
  }
  </code></pre>
  
  <p>Directory.GetFiles
  <a href="http://msdn.microsoft.com/en-us/library/wz42302f.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/wz42302f.aspx</a></p>
  
  <p>This method has already been posted a few times:
  <a href="https://stackoverflow.com/questions/1288718/c-how-to-delete-all-files-and-folders-in-a-directory">How to delete all files and folders in a directory?</a>
  and
  <a href="https://stackoverflow.com/questions/1620366/c-delete-files-from-directory-if-filename-contains-a-certain-word">Delete files from directory if filename contains a certain word</a></p>
  
  <p>But the problem with this method is that if you have say a hundred thousand files it becomes a performance issue as it has to generate all of the filepaths first before looping through them.</p>
  
  <p>Added to this if a web page is waiting a response from a method which is performing this as you can imagine it will look a bit rubbish!</p>
  
  <p>One thought I had was to wrap this up in an an asychrnonous web service call and when it completes it fires back a response to the web page to say that they have been removed? Maybe put the delete method in a separate thread? Or maybe even use a seperate batch process to perform the delete?</p>
  
  <p>I have a similar issue when trying to count the number of files in a directory - if it contains a large number of files.</p>
  
  <p>I was wondering if this is all a bit overkill? I.e. is there a simpler method to deal with this? Any help would be appreciated.</p>