Fun with System.IO.Directory.Delete

So, here's a small gotcha I ran into while using this API not too long ago.

System.IO.Directory.Delete has some interesting nuances (what happens with mounts?) - it's definitely worth reading. Something that is not currently in the documentation is the behavior when files or directories are marked read-only within. In short - the operation stops when the file or directory is encountered, and an exception is thrown. Interestingly, the exception may be UnauthorizedAccessException or IOException, depending on whether it is a file or directory that had the attribute.

Removing the attribute is a straightforward task with File.SetAttributes:

File attributes = File.GetAttributes(path);
if ((attributes & FileAttributes.ReadOnly) != 0)
  File.SetAttributes(path, attributes & ~FileAttributes.ReadOnly);

Comments (0)

Skip to main content