Monday, November 24, 2008

Directory.Delete and Read-only Files

The System.IO.Directory.Delete() method will fail (exception) when it encounters a read-only file, regardless of the recursive flag. Unfortunately, the designers of this method did not have the foresight to provide a means around this limitation.

First off, the exception (UnauthorizedAccessException) only contains the file name; no path information is given. So, if you are in the middle of a recursive delete, the file name is largely irrelevant and there isn't much (programatically) that can be done to manage the situation. The appropriate implementation would have been to include the full path & file name information in the exception, and let the implementor decide on how to represent the file to the UI, as needed.

Second, there is no provision to handle read-only or similar situations w/ the method. At a minimum, there should be the capability to specify whether or not a read-only file should be deleted or not.

Because of this, the recursive implementation of Directory.Delete() is largely useless as it doesn't do what it has been designed to do: delete a directory (and containing files). The consequence of this is that we must write our own method to perform what is actually wanted -- hardly efficient. Anyway, to that end, here is a small function that implements more complete and usable delete functionality:

  public void DirectoryDelete(string path, bool recursive)
  {
    if (recursive)
      foreach (string directory in Directory.GetDirectories(path))
        DirectoryDelete(directory, true);
    foreach (string file in Directory.GetFiles(path))
      File.SetAttributes(file, FileAttributes.Normal);
    Directory.Delete(path, true);
  }

No comments: