Wednesday, July 15, 2009

IOException While Trying to Delete a Folder?!

Make sure you don't step on your own toes. The following code illustrates...


using System;
using System.IO;

internal class Program
{
private static void Main(string[] args)
{
string directory = @"C:\atemporaryfolder\";
Directory.CreateDirectory(directory);
Environment.CurrentDirectory = directory;
Directory.Delete(directory);
}
}


Who's using the folder? You are. Whenever Environment.CurrentDirectory is set in an application, it prevents anything else from deleting the folder. Note that the Environment.CurrentDirectory can also be set through a variety of other means, including the FolderBrowserDialog, OpenFileDialog and SaveFileDialog.

What's the solution? Simple. Set Environment.CurrentDirectory to something else. @"C:\" works just fine.