Tuesday, March 30, 2010

Annoyances with C#'s DirectoryInfo.Delete()

Taking a small break from writing up a game design doc for my iPhone game. It's interesting being the one actually writing a doc for a game, rather than reading one made by someone else. It does make me appreciate the amount of thought and work our designers put in.

Anyway, last week at work I was writing a new C# console utility to automate directory clean-up tasks on our build server. Things went pretty well until I hit a snag with DirectoryInfo.Delete(Boolean) not working properly and throwing a constant stream of exceptions. It ends up it was error'ing out because the directories I was trying to delete (which contain a good number of sub-directories of arbitrary depths, and several thousand files), contained a number of read-only files. After looking around a bit, it appears this is intended behavior, as it follows the idea of the pop-up notification users get when they try to manually delete directories.

To get around this, I ended up creating a simple method to iterate through all directories and files under a particular directory, and set all their Attributes to normal. Sorry for the formatting.

// Set attributes on all dirs and files in the passed in directory to 'Normal'
void SetDirectoryContentsToNormal ( DirectoryInfo Dir )
{
if ( Dir.Exists )
{
Dir.Attributes = FileAttributes.Normal;
DirectoryInfo[] SubDirs = Dir.GetDirectories("*", SearchOption.AllDirectories);

foreach ( DirectoryInfo SubDir in SubDirs )
{
SubDir.Attributes = FileAttributes.Normal;
}

FileInfo[] FilesInDir = Dir.GetFiles("*", SearchOption.AllDirectories);

foreach ( FileInfo file in FilesInDir )
{
file.Attributes = FileAttributes.Normal;
}
}
}

This does cause a little pause when running, however for our particular circumstance it's perfectly fine because the tool runs only once a day in the early morning.

No comments:

Post a Comment