.NET bin and obj Directory Cleaner
Because I write a lot of blog posts, I have a lot of .NET projects on my disks. After building or running each project, a bin and obj directory is created. These directories take up a lot of space, and if I want to copy projects from one disk to another, they slow down the copy because of the number of files in these directories.
Here is a .NET CLI tool that will print out delete commands for all the bin and obj directories in a given directory.
It doesn’t run the commands. You should review them before you run them.
1#!/usr/bin/env -S dotnet --
2#:sdk Microsoft.NET.Sdk
3
4var isPowerShell = Environment.GetEnvironmentVariable("PSModulePath") != null;
5if (isPowerShell && (args.Length == 0 || args[0] == "."))
6{
7 Console.Error.WriteLine("PowerShell does not propagate its current directory to child processes.");
8 Console.Error.WriteLine("Pass an absolute path or $PWD, e.g.: DotNetBinObjCleaner.cs $PWD");
9 return 1;
10}
11
12var invocationDir = Environment.GetEnvironmentVariable("PWD") ?? Directory.GetCurrentDirectory();
13var startDir = args.Length > 0 ? Path.GetFullPath(args[0], invocationDir) : invocationDir;
14
15if (args.Length == 0)
16{
17 Console.Write($"Start search in current directory '{startDir}'? [y/N] ");
18 var response = Console.ReadLine()?.Trim().ToLower();
19 if (response != "y")
20 {
21 Console.WriteLine("Aborted.");
22 return 0;
23 }
24}
25
26if (!Directory.Exists(startDir))
27{
28 Console.Error.WriteLine($"Error: directory not found: {startDir}");
29 return 1;
30}
31
32var projectDirs = new List<string>();
33FindProjectDirs(startDir, projectDirs);
34
35var toDelete = new List<string>();
36foreach (var dir in projectDirs)
37{
38 foreach (var name in new[] { "bin", "obj" })
39 {
40 var path = Path.Combine(dir, name);
41 if (Directory.Exists(path))
42 toDelete.Add(path);
43 }
44}
45
46if (toDelete.Count == 0)
47{
48 Console.WriteLine("No bin/obj folders found.");
49 return 0;
50}
51
52Console.WriteLine("# PowerShell");
53foreach (var path in toDelete)
54 Console.WriteLine($"Remove-Item -Recurse -Force '{path}'");
55
56Console.WriteLine();
57
58Console.WriteLine("# Bash");
59foreach (var path in toDelete)
60 Console.WriteLine($"rm -rf '{path}'");
61
62return 0;
63
64void FindProjectDirs(string dir, List<string> results)
65{
66 if (Directory.GetFiles(dir, "*.csproj").Length > 0)
67 {
68 results.Add(dir);
69 return;
70 }
71
72 try
73 {
74 foreach (var sub in Directory.GetDirectories(dir))
75 FindProjectDirs(sub, results);
76 }
77 catch (UnauthorizedAccessException) { }
78}Save this to a file to a directory that is in your PATH and you can run it from anywhere.
That’s it, easy cleanup of your .NET projects.