Monday, March 9, 2009

Deleting .svn Folders for Subversion Using C#

This past weekend I needed the ability to programmatically delete the .svn folders used by subversion in my project. I created some code in C# to change the subversion files to be writable and delete them.

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 directories

list = Directory.GetFileSystemEntries(folderPath, wildcardPattern);


foreach (string item in list)

{

//Sub directories

if (Directory.Exists(item))

{

//Match all sub directories

DeleteSubFolders(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);

}

}


5 comments:

Matt Mc said...

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);
}
}

Greg Finzer said...

Matt, thanks that is very cool. That is much more compact.

Mike Wood said...

Thanks for sharing!

Anonymous said...

I'm sure you have a pretty good reason, but... why not just use svn export command instead?

Greg Finzer said...

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.