Introduction
This article gives idea how to use recursion to delete specific directory inside a root directory.
Using the code
DeleteBinAndObj is the method used to delete all bin and obj folders inside ..Projects folder.
DeleteBinAndObj(@"C:\Users\Documents\Visual Studio 2010\Projects");
It gets the current folder info using System.IO.DirectoryInfo class and also keeps the information of sub-directories inside it in an array System.IO.DirectoryInfo[]. If there are any sub directories then the method call itself (recursion) by passing the current sub directory.
foreach (DirectoryInfo myItem in subfolders)
DeleteBinAndObj(myItem.FullName);
If there are no sub directories then the current directory name will be compared with the specific string and if it matches the current directory is deleted using Directory.Delete method
if(rootFolder.Name.Equals("bin") || rootFolder.Name.Equals("Bin") || rootFolder.Name.Equals("BIN")
||rootFolder.Name.Equals("obj") || rootFolder.Name.Equals("Obj") || rootFolder.Name.Equals("OBJ"))
Directory.Delete(rootFolder.FullName, true);
If a file inside a directory does not have enough permission to delete then the directory will not be deleted and Directory.Delete(...) method throws exception. So you can use a try-catch block to handle this situation.
try
{
Directory.Delete(rootFolder.FullName, true);
}
catch
{
return;
}
The final code would look like this,
using System.IO;
namespace DeleteFolder
{
class Program
{
static void Main(string[] args)
{
DeleteBinAndObj(@"C:\Users\Documents\Visual Studio 2010\Projects");
}
private static void DeleteBinAndObj(string rootPath)
{
DirectoryInfo rootFolder = new DirectoryInfo(rootPath);
DirectoryInfo[] subfolders = rootFolder.GetDirectories();
foreach (DirectoryInfo myItem in subfolders)
DeleteBinAndObj(myItem.FullName);
if (rootFolder.Name.Equals("bin") || rootFolder.Name.Equals("Bin") || rootFolder.Name.Equals("BIN") ||
rootFolder.Name.Equals("obj") || rootFolder.Name.Equals("Obj") || rootFolder.Name.Equals("OBJ"))
{
try
{
Directory.Delete(rootFolder.FullName, true);
}
catch
{
return;
}
}
}
}
}