Delete dotnet bin and obj folders recursively

Date Published: 20 December 2022

Delete dotnet bin and obj folders recursively

Although Visual Studio and the dotnet CLI both offer clean commands, neither one really cleans up bin and obj files generated by the build process, and often things are left behind that cause problems. Here's how to really remove all bin and obj folders recursively.

Scenario

You want to remove all bin and obj folders from your solution or git repo. Sometimes there are files in the bin and/or obj folders that cause problems. Other times you're trying to remove these folders and their contents in order to avoid checking unnecessary things into source control. And sometimes you just want to eliminate unnecessary files so that you can create a ZIP archive to store or send to someone that is as small as possible.

In any of these cases, using the built-in Visual Studio Clean or dotnet clean commands may not be sufficient. While these generally provide a "good enough" experience, it's kind of like the refresh button in the browser. Sometimes you really need the "no, seriously, clear everything and reload it fresh" nuclear option.

"Which build artifact files and folders should we delete?"

"EVERY ONE!"

gary oldman saying everyone from The Professional

Here are some options for this case.

Powershell

Assuming you have Powershell available, I've found the following script to be very useful. Often enough that I'm now blogging about it here so that I can easily find it in the future:

Get-ChildItem .\ -include bin,obj -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse }

The original source of this script also includes options for bash/zsh and Windows cmd versions, though I rarely need those.

A slightly more compact version is:

gci -exclude "*.dll" -include bin,obj -recurse | remove-item -force -recurse

If you want to put the commands into a batch file (for cmd usage or from Windows Explorer double-click) this script should do the trick (NOTE it does not use the recycle bin or confirm before deletion!):

for /d /r . %d in (bin,obj) do @if exist "%d" rd /s/q "%d"

You can make it a bit safer if you remove /q.

References

Steve Smith

About Ardalis

Software Architect

Steve is an experienced software architect and trainer, focusing on code quality and Domain-Driven Design with .NET.