Skip to content

Instantly share code, notes, and snippets.

@marta-krzyk-dev
Last active April 5, 2019 08:51
Show Gist options
  • Save marta-krzyk-dev/70498bba6bf9608b37a77a6bd86ece03 to your computer and use it in GitHub Desktop.
Save marta-krzyk-dev/70498bba6bf9608b37a77a6bd86ece03 to your computer and use it in GitHub Desktop.
Remove all subfolders with given name within a folder
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RemoveFolders
{
class Program
{
private const string exitCode = "0";
static void Main(string[] args)
{
while(DeleteFolders())
{
Console.WriteLine();
Console.WriteLine();
}
}
private static bool DeleteFolders()
{
Console.WriteLine("This program removes all obj, bin and vs subfolders in a given folder.");
Console.WriteLine($"Type {exitCode} to exit the program.");
Console.Write("Path to folder: ");
string folderPath = Console.ReadLine();
if (folderPath == exitCode)
return false;
try
{
IEnumerable<string> foldersToRemove =
Directory.GetDirectories(folderPath, "obj", SearchOption.AllDirectories)
.Union(Directory.GetDirectories(folderPath, "bin", SearchOption.AllDirectories))
.Union(Directory.GetDirectories(folderPath, ".vs", SearchOption.AllDirectories));
int i = 0;
foreach (string folder in foldersToRemove)
{
try
{
Directory.Delete(folder, true);
Console.WriteLine($"{++i}.\tDeleted {folder}");
}
catch (IOException exception)
{
Console.WriteLine($"Error: {folder} - {exception.Message}");
}
}
Console.WriteLine($"Deleted {i} folders.");
}
catch (DirectoryNotFoundException)
{
Console.WriteLine($"{folderPath} not found.");
}
catch (Exception exception)
{
Console.WriteLine($"Error: {exception.Message}");
}
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment