Delete all files in BIN and OBJ folders recursive

Programming VisualStudio C#

From times to times we want to archive all of our sources into a ZIP file on some drive.  We just want to archive the source code and of course not the binaries which would increase the size of the ZIP file enormously.  Therefore we have to delete all files in the /BIN and /OBJ folders of all our projects.

Given a project structure like this

project structure

a command line tool like this

$> ClearBinVS W:\WOLFSYS\SOURCES

would be very handy.  No problem, that can be solved with a little console application in C# (you could also write a shell or PS script of course):

using System;
using System.IO;

namespace wolfSYS.Util.ClearBinVS
{
class Program
{
static void Main(string[] args)
{
var path = DetectParentFolder(args);

if (!string.IsNullOrEmpty(path))
{
int nr = ScannBinObjFolders(path);

if (nr > 0)
{
Console.WriteLine("");
Console.WriteLine($"ClearBinVS finished, deleted {nr} files.");
}
else
{
Console.WriteLine("ClearBinVS finished, no files have been deleted.");
}
}
else
{
Console.WriteLine("ClearBinVS had nothing to do.");
}
}

// delete all files in /BIN and /OBJ folders recursive
static int ScannBinObjFolders(string folderToScan)
{
int cnt = 0;
try
{
string[] files = Directory.GetFiles(folderToScan, "*.*", SearchOption.AllDirectories);

foreach(var f in files)
{
FileInfo fi = new FileInfo(f);

var dir = fi.Directory.ToString().ToLower();
if (dir.Contains(@"\bin\") || dir.Contains(@"\obj\"))
{
Console.WriteLine(fi.FullName);
File.Delete(fi.FullName);
cnt++;
}
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
return cnt;
}

static string DetectParentFolder(string[] args)
{
string res = "";

if (args.Length > 1)
{
Console.WriteLine("ClearBinVS usage:");
Console.WriteLine("");
Console.WriteLine("$> ClearBinVS <AbsolutPath> ... delete recursive in given path");
Console.WriteLine("$> ClearBinVS ................. delete recursive in current folder");
}
else
{
if (args.Length == 1)
{
if (Directory.Exists(args[0]))
res = args[0];
}
else
{
res = Directory.GetCurrentDirectory();
Console.WriteLine("ClearBinVS using current folder:");
Console.WriteLine($" {res}");
Console.WriteLine("");
}
}

return res;
}
}
}

Consider that in a real world scenario you'll probably have to delete files in more folders than just /BIN and /OBJ (like f.e. the content in the publishing folder).