I am a danish programmer living in Bangkok.
Read more about me @ rasmus.rummel.dk.
Webmodelling Home > ASP.NET > C# Utility Functions > IO - ClearFolder

ClearFolder

.Net Framework does not have a function that can delete all contents of a folder, eg. if you try DirectoryInfo.Delete(true); and the hierachy have any content, then it will fail with "Directory is not empty". This means we have to write a recursive delete function each time we want to clear a directory hierarchy.

References :

Usage

  • Example
    • I use the ClearFolder function on menulab.com to delete orphaned Compact Edition database files that are left overs of the Discussions server control examples.
  • Example Code
    • string sessionsPath = Server.MapPath("~/_menulab/Discussions/Sessions");
      if (System.IO.Directory.Exists(sessionsPath))
      {
      	ClearFolder(sessionsPath);
      }
      

The ClearFolder function :

public static void ClearFolder(string pFolderPath)
{
	DirectoryInfo dirInfo = new DirectoryInfo(pFolderPath);

	FileInfo[] fileInfos = dirInfo.GetFiles();
	foreach (FileInfo fileInfo in fileInfos)
	{
		if (!fileInfo.IsReadOnly)
		{
			fileInfo.Delete();
		}
	}

	DirectoryInfo[] subDirInfos = dirInfo.GetDirectories();
	foreach (DirectoryInfo subDirInfo in subDirInfos)
	{
		ClearFolder(subDirInfo.FullName);
		subDirInfo.Delete();
	}
}

Comments

You can comment without logging in
Profile
Username
Password
Password
Email
Nickpic
Get notified on reply to own posts  (only works if you specify an email address)
Get notified on receiving a PM  (only works if you specify an email address)
Remember my username
Remember my password
signature
Words: Chars: Chars left: