How to fully clean bin and obj folders within Visual Studio?

Viewed 139511

If you right click on a folder, you will see a "Clean" menu item. I assumed this would clean (remove) the obj and bin directory. However, as far as I can see, it does nothing. Is there another way? (please don't tell me to go to Windows Explorer or the cmd.exe) I'd like to remove the obj and bin folder so that I can easily zip the whole thing.

23 Answers

For Visual Studio 2015 the MSBuild variables have changed a bit:

  <Target Name="SpicNSpan" AfterTargets="Clean"> <!-- common vars https://msdn.microsoft.com/en-us/library/c02as0cs.aspx?f=255&MSPPError=-2147217396 -->
         <RemoveDir Directories="$(TargetDir)" /> <!-- bin -->
         <RemoveDir Directories="$(SolutionDir).vs" /> <!-- .vs -->
         <RemoveDir Directories="$(ProjectDir)$(BaseIntermediateOutputPath)" /> <!-- obj -->
  </Target>

Notice that this snippet also wipes out the .vs folder from the root directory of your solution. You may want to comment out the associated line if you feel that removing the .vs folder is an overkill. I have it enabled because I noticed that in some third party projects it causes issues when files ala application.config exist inside the .vs folder.

Addendum:

If you are into optimizing the maintainability of your solutions you might want to take things one step further and place the above snippet into a separate file like so:

  <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
       <Target Name="SpicNSpan" AfterTargets="Clean"> <!-- common vars https://msdn.microsoft.com/en-us/library/c02as0cs.aspx?f=255&MSPPError=-2147217396 -->
            <RemoveDir Directories="$(TargetDir)" /> <!-- bin -->
            <RemoveDir Directories="$(SolutionDir).vs" /> <!-- .vs -->
            <RemoveDir Directories="$(ProjectDir)$(BaseIntermediateOutputPath)" /> <!-- obj -->
       </Target>
  </Project>

And then include this file at the very end of each and every one of your *.csproj files like so:

     [...]
     <Import Project="..\..\Tools\ExtraCleanup.targets"/>
  </Project>

This way you can enrich or fine-tune your extra-cleanup-logic centrally, in one place without going through the pains of manually editing each and every *.csproj file by hand every time you want to make an improvement.

Visual Studio Extension

enter image description here

Right Click Solution - Select "Delete bin and obj folders"

It doesn't remove the folders, but it does remove the build by-products. Is there any reason you want the actual build folders removed?

In windows just open the explorer navigate to your SLN folder click into search field and type kind:=folder;obj --> for obj folders use CTRL+A and delete 'em - same for bin Done

No need for any tool or extra software ;)

Clean will remove all intermediate and final files created by the build process, such as .obj files and .exe or .dll files.

It does not, however, remove the directories where those files get built. I don't see a compelling reason why you need the directories to be removed. Can you explain further?

If you look inside these directories before and after a "Clean", you should see your compiled output get cleaned up.

Update: Visual Studio 2019 (Clean [bin] and [obj] before release). However I am not sure if [obj] needs to be deleted. Be aware there is nuget package configuration placed too. You can remove the second line if you think so.

<Target Name="PreBuild" BeforeTargets="PreBuildEvent" Condition="'$(Configuration)' == 'Release'">
  <!--remove bin-->
  <Exec Command="rd /s /q &quot;$(ProjectDir)$(BaseOutputPath)&quot; &amp;&amp; ^" />
  <!--remove obj-->
  <Exec Command="rd /s /q &quot;$(BaseIntermediateOutputPath)Release&quot;" />
</Target>

I store my finished VS projects by saving only source code.

I delete BIN, DEBUG, RELEASE, OBJ, ARM and .vs folders from all projects.

This reduces the size of the project considerably. The project

must be rebuilt when pulled out of storage.

Just an addendum to all the fine answers above in case someone doesn't realize how easy it is in VB/C# to automate the entire process down to the zip archive.

So you just grab a simple Forms app from the templates (if you don't already have a housekeeping app) and add a button to it and then ClickOnce install it to your desktop without worrying about special settings or much of anything. This is all the code you need to attach to the button:

Imports System.IO.Compression

Private Sub btnArchive_Click(sender As Object, e As EventArgs) Handles btnArchive.Click
    Dim src As String = "C:\Project"
    Dim dest As String = Path.Combine("D:\Archive", "Stub" & Now.ToString("yyyyMMddHHmmss") & ".zip")
    If IsProjectOpen() Then 'You don't want Visual Studio holding a lock on anything while you're deleting folders
        MsgBox("Close projects first, (expletive deleted)", vbOKOnly)
        Exit Sub
    End If
    If MsgBox("Are you sure you want to delete bin and obj folders?", vbOKCancel) = DialogResult.Cancel Then Exit Sub
    If ClearBinAndObj(src) Then ZipFile.CreateFromDirectory(src, dest)
End Sub

Public Function ClearBinAndObj(targetDir As String) As Boolean
    Dim dirstodelete As New List(Of String)
    For Each d As String In My.Computer.FileSystem.GetDirectories(targetDir, FileIO.SearchOption.SearchAllSubDirectories, "bin")
        dirstodelete.Add(d)
    Next
    For Each d As String In My.Computer.FileSystem.GetDirectories(targetDir, FileIO.SearchOption.SearchAllSubDirectories, "obj")
        dirstodelete.Add(d)
    Next
    For Each d In dirstodelete
        Try
            Directory.Delete(d, True)
        Catch ex As Exception
            If MsgBox("Error: " & ex.Message & " - OK to continue?", vbOKCancel) = MsgBoxResult.Cancel Then Return False
        End Try
    Next
    Return True
End Function

Public Function IsProjectOpen()
    For Each clsProcess As Process In Process.GetProcesses()
        If clsProcess.ProcessName.Equals("devenv") Then Return True
    Next
    Return False
End Function

One thing to remember is that file system deletes can go wrong easily. One of my favorites was when I realized that I couldn't delete a folder because it contained items created by Visual Studio while running with elevated privileges (so that I could debug a service).

I needed to manually give permission or, I suppose, run the app with elevated privileges also. Either way, I think there is some value in using an interactive GUI-based approach over a script, specially since this is likely something that is done at the end of a long day and you don't want to find out later that your backup doesn't actually exist...

this answer is great I just want to comment on the last part of the answer

NOTE : You should have this stored in a PowerShell file and place that file at the root of your solution (where the .sln file resides), and then run it when you want a proper clean (not the micky mouse one that VisualStudio does, and reports success too).

Alternatively, you can add the following to your profile.ps1

function CleanSolution {
    Get-ChildItem -inc bin,obj -rec | Remove-Item -rec -force
}

Set-Alias cs CleanSolution 

Then you can use either CleanSolution or cs to run. That way you can use it for any project and without the ./ prefix of the filename

Complete one-liner you can invoke from within Visual Studio

In your solution root folder create a file called "CleanBin.bat" and add the following one-liner:

Powershell.exe -ExecutionPolicy Bypass -NoExit -Command "Get-ChildItem -inc bin,obj -rec | Remove-Item -rec -force"

Run the .bat file. Enjoy.

Original creds to the answer here: https://stackoverflow.com/a/43267730/1402498 The original answer shows the powershell command, but I had a lot of trouble making it work smoothly on my system. I finally arrived at the one-liner above, which should work nicely for most folks.

Caveat: Microsoft seems to be great at making Windows security cause stranger and stranger behavior. On my machine, when I run the script, all obj and bin folders are deleted but then reappear 2 seconds later! Running the script a second time causes permanent deletion. If anyone knows what would cause this behavior, please let me know a fix and I'll update the answer.

If you need to delete bin and obj folders from ALL of your projects...

Launch git Bash and enter the following command:

find . -iname "bin" -o -iname "obj" | xargs rm -rf

For C# projects, I recommend appending $(Configuration) to obj folder, so-as to avoid deleting nuget files which are stored on obj base directory.

<Target Name="CleanAndDelete"  AfterTargets="Clean">
    <!-- Remove obj folder -->
    <RemoveDir Directories="$(BaseIntermediateOutputPath)$(Configuration)" />
    <!-- Remove bin folder -->
    <RemoveDir Directories="$(BaseOutputPath)" />
</Target>

If you delete the nuget files, it can be problematic to recreate them. Moreover, I've never seen a case where "Restore NuGet Packages" fixes this issue after these files have been deleted.

Related