Here is how to use it:
DeleteSubFolders(@"c:\svn\MyProject\Trunk",".svn",true);
Here is the code:
public static void DeleteSubFolders(string folderPath, string wildcardPattern, bool top)
{String[] list;
//If we are at the top level, get all directory names that match the pattern
if (top)list = Directory.GetDirectories(folderPath, wildcardPattern, SearchOption.AllDirectories);
else //Get directories and files for matching sub directorieslist = Directory.GetFileSystemEntries(folderPath, wildcardPattern);
foreach (string item in list)
{//Sub directories
if (Directory.Exists(item)){
//Match all sub directoriesDeleteSubFolders(item, "*", false);
}else // Files in directory
{//Get the attribute for the file
FileAttributes fileAtts = File.GetAttributes(item);//If it is read only make it writable
if ((fileAtts & FileAttributes.ReadOnly) != 0)
{File.SetAttributes(item, fileAtts & ~FileAttributes.ReadOnly);
}File.Delete(item);
}
}//Delete the matching folder that we are in
if (top == false)
{Directory.Delete(folderPath);
}}
6 comments:
Good stuff Greg! I've had to do something similar before too. The System.IO API has some good stuff in it that might help make your code a little tighter. I took a crack at it myself, and I could get it with a double loop instead of recursion. Not sure which is more performant or if that's even a concern. Not sure I can format it well, but it's 8 lines if you count the braces.
public static void DeleteSubFolders(string folderPath, string wildcardPattern) {
foreach (string dirpath in Directory.GetDirectories(folderPath, wildcardPattern, SearchOption.AllDirectories)) {
foreach (string filePath in Directory.GetFiles(dirpath, "*.*", SearchOption.AllDirectories)) {
File.SetAttributes(filePath, FileAttributes.Normal);
}
Directory.Delete(dirpath, true);
}
}
Matt, thanks that is very cool. That is much more compact.
Thanks for sharing!
I'm sure you have a pretty good reason, but... why not just use svn export command instead?
I didn't know that the export command existed. I don't really need it now since I already have this delete sub folders as part of my automated build process.
Thanks man, this works.
Post a Comment