How to fully clean bin and obj folders within Visual Studio?
Solution 1
As others have responded already Clean will remove all artifacts that are generated by the build. But it will leave behind everything else.
If you have some customizations in your MSBuild project this could spell trouble and leave behind stuff you would think it should have deleted.
You can circumvent this problem with a simple change to your .*proj by adding this somewhere near the end :
<Target Name="SpicNSpan"
AfterTargets="Clean">
<RemoveDir Directories="$(OUTDIR)"/>
</Target>
Which will remove everything in your bin folder of the current platform/configuration.
------ Edit Slight evolution based on Shaman's answer below (share the votes and give him some too)
<Target Name="SpicNSpan" AfterTargets="Clean">
<!-- Remove obj folder -->
<RemoveDir Directories="$(BaseIntermediateOutputPath)" />
<!-- Remove bin folder -->
<RemoveDir Directories="$(BaseOutputPath)" />
</Target>
---- Edit again with parts from xDisruptor but I removed the .vs deletion as this would be better served in a .gitignore (or equivalent)
Updated for VS 2015.
<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="$(ProjectDir)$(BaseIntermediateOutputPath)" /> <!-- obj -->
</Target>
He also provides a good suggestion on making the task easier to deploy and maintain if you have multiple projects to push this into.
If you vote this answer be sure to vote them both as well.
Solution 2
If you are using git and have a correct .gitignore in your project, you can
git clean -xdf --dry-run
to remove absolutely every file on the .gitignore list, i.e. it will clean obj, and bin folders (the x triggers this behavior)
Note: The parameter --dry-run will only simulate the operation ("Would remove ...") and show you what git would delete. Try it with dry-run, then remove the parameter and it will really delete the files+folders.
Optionally, after that clean command, you can use dotnet restore mySolution.sln to get all the NUGET packages restored. And if you have a developer console open anyway,
you can quickly run msbuild -m mySolution.sln afterwards (without having Visual Studio open) to see if it was successful.
Solution 3
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.
Solution 4
To delete bin and obj before build add to project file:
<Target Name="BeforeBuild">
<!-- Remove obj folder -->
<RemoveDir Directories="$(BaseIntermediateOutputPath)" />
<!-- Remove bin folder -->
<RemoveDir Directories="$(BaseOutputPath)" />
</Target>
Here is article: How to remove bin and/or obj folder before the build or deploy
Solution 5
This site: https://sachabarbs.wordpress.com/2014/10/24/powershell-to-clean-visual-studio-binobj-folders/ uses William Kempf's powershell commands to remove any bin and obj folders from the current directory and sub directories. It should be possible to run it from the root of the drive.
Here is William's version
gci -inc bin,obj -rec | rm -rec -force
In William's own words:
That wipes out all of the “bin” and “obj” directories in the current directory and every subdirectory. Super useful to run in your workspace directory to get to a “clean” state, especially when someone messes up and there’s something that a Clean or Rebuild inside the IDE doesn’t catch.
For those of you reading that may not know, PowerShell supports command aliases, here it is rewritten again not using the aliases
Get-ChildItem -inc bin,obj -rec | Remove-Item -rec -forceNOTE : 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).
Related videos on Youtube
tom7
Updated on July 08, 2022Comments
-
tom7 6 monthsIf 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.
-
Michael Freidgeim over 5 yearsPossible duplicate of I want to delete all bin and obj folders to force all projects to rebuild everything -
Philip Oakley over 1 yearIf built by CMake (CMakeLists.txt) then there can also be a 'CMakeSettings.json' file. This was, for me, one level up from thevcpkginstall sub-dir. That file wasn't part of the project's .gitignore so was confusing for Ruben'sgit clean ...method.
-
-
tom7 over 13 yearsI'd like to remove everything that's not necessary to compilation so that I can zip it and send it. Having .exes in zip files can be a problem for anti viruses. -
tom7 over 13 yearsI want to remove bin and obj directories in order to zip everything. -
tom7 over 13 years"Clean" does not remove the .exe. -
abelenky over 13 yearsJust tried it with my Visual Studio 2005, and I can verify that "Clean" did remove the .exe (and all other files). -
Christopher over 13 yearsYes. But as I said, the build products are removed. That means the .obj and .exe files. Just not the actual folders. -
Keith Hoffman over 10 yearsIn Visual Studio 2010, maybe. Right now, I can confirm that a "Clean Solution" does not remove dlls from the Debug/bin folders. -
Newtopian over 10 yearsClean does not delete files if they are not computed by the build. If some files travel to the outdir by some other mecanism then clean will not delete them. In other words, when wearing build manager`s hat, clean is completely and utterly useless, dangerous even. -
Rolf almost 10 yearsThis is the best solution, works, doesn't require special tools and makes sure every teammember uses the same "clean" method. Why MS Visual Studio doesn't clean properly is a complete mystery to me. -
tomoguisuru over 9 yearsThis is by far the easiest solution to implement and gets the job done without any external plugins -
aliceraunsbaek almost 9 yearsNot sure how to activate/call this target. Just choosing 'Clean' does not appear to do anything. So how do I use it? -
Newtopian over 8 yearssorry just now saw your comment. Specifying AfterTargets="Clean" will hook the target to the internal clean target for VisualStudio. However this simple target does not provide any feedbaco to the console so it will not do much other than wiping out your $(OUTDIR) from existence. You can add some error management and messages to it and get some better feedback. -
Newtopian over 8 yearsI like the idea of removing the intermediaries as well, however there are significant side effects to hooking at BeforeBuild as it will wipe all possibilities to perform incremental builds. In projects that take significant amount of time to build this is a show stopper. Also by wiping out the base output dir you may interfere with tools that may want to perform multi-target/configuration builds and cumulate the results prior to packaging it for deployment, here only the last build performed will survive. -
CAD bloke over 8 yearsI tried this in VS 2013 and it actually added folders to \bin & \obj. Caveat: my .csproj imports a few external .csproj files with build configurations - there are 26 builds, each of which goes in a subfolder under \obj / \bin (I can explain!). -
Newtopian over 8 yearsMystery to me how RemoveDirectory can add directory ! I would think it probably a side effect of something else in your MSbuild tasks, perhaps the folders are created automatically after a clean has been called -
Randy P. over 7 yearsWe had a phantom orphaned assembly, adding this to the end of our .csproj did exactly what the OP suggested and it fixed our issue. Love how clean the solution is! -
Ehtesh Choudhury almost 6 yearsThis works beautifully. Very convenient when you want to do solution wide instead of just one Visual Studio project -
iokevins over 5 yearsIn Microsoft Visual Studio Community 2017 v15.3.4 (run as Administrator), removing folder ".vs" gives error, "Unable to remove directory "{SOLUTIONDIR}\.vs". The process cannot access the file 'storage.ide' because it is being used by another process." I can remove after exiting Visual Studio, but it re-appears after restart. I've commented out that line, as it's not needed for my use case. -
Newtopian almost 5 yearsyeah, I would not recommend deleting the IDE's working folder during execution. As I've stated in the answer this should probably be handled with an entry in a gitignore file (or whatever equivalent for your SCM of choice) -
Oli4 almost 5 yearsIf some of the references were removed/moved and the dll's were not referenced in code, they are no longer built into the bin folders, however they are not cleaned either. This ends up in a local vs of your application that builds, but fails everywhere else. -
Reinier Torenbeek almost 5 years@JoeHealy In stead of cleaning first and then zipping, it might be easier to use git-archive to zip directly from the repo. -
brett over 4 yearsWorks like a charm! This is the best answer. Also if, let's say the project is not using source control, this answer still aplies: just add the project to source control (right click on solution name), then run the git command above. Btw, how do you use git commands in Windows? I had to use Bash on Ubuntu on Windows. -
Raymond over 4 years@brett Interesting ;) I typically use GitHub for Windows to pave (though I'm pretty sure VS installs a working rig that can be used from VS command prompt) - the settings lets you select a shell arrangement (from which I choose PoshGit). Using WSL is the most educational, so good call! -
Loudenvier over 4 yearsBe aware that if you use a version control system like mercurial and it is in the same directory level as this script, this script will corrupt your repository if you store anything on it inside a "bin" folder ... otherwise this is a very useful script! -
mkb about 4 yearsas I understand-xdfand-d -f -xmeans the same thing but I only got successfull result withgit clean -d -f -xcommand. When I use-xdfit only saysWould remove \somedirectory. Can anyone explain it? -
mkb about 4 yearsok. now I see; the key is--dry-run, this will only tells you what's gonna be deleted. nice -
Raymond about 4 years@mbk correct ;) ... a less cryptic writeup I saw recently: jerriepelser.com/blog/… -
Vlad about 4 yearsgoogled this question looking for automatic solution specifically to stop manually doing it in FAR Manager lol -
crokusek about 3 yearsFor me, this answer only cleaned the files within an ignored directory and did not recursively clean sub directories within an ignore. Like it cleaned bin files but not bin/Debug/* -
Raymond about 3 years@crokusek that suggests that your.gitignoreis inconsistent in some way - thegit cleanis pretty predictable and GIGO -
Tim Sparkles almost 3 years@Rolf Visual Studio doesn't clean "properly" by default because MS has to support the use case where N different projects output to the same directory. If cleaning a project clobbered its entire output directory by default, it could clobber files entirely unrelated to that project. So instead the default behavior is to keep track of files that are actually output by the build process and delete only those files on clean. A common class of breakage at clean time is caused by creating or copying a file during the build without telling MSBuild to add it to the tracking list. -
brett almost 3 years@crokusek you could make a copy of the project directory somewhere, delete all .git files, including .gitignore in the new directory and open the cloned project with Visual Studio. With right click on solution name add the project to source control. This will generate correct .gitignore file. You will then be able to run the command on this repository and clean up the extra files not really necessary for archiving the project. -
progLearner almost 3 yearsIs there any nice way to delete all files in a folder except from one specific one? -
XDS almost 3 years@progLearner ofcourse there is stackoverflow.com/a/10019708/863651 -
progLearner almost 3 yearsAlso, I noticed there are sometimes some file locks on some dll from the bin directory. Is there a way to force file deletion? -
XDS almost 3 years@progLearner it's a tricky question to answer properly. Some files appear to be locked yet if we persist 2 or 3 times then they do get deleted. Then there are cases where files are truly locked indeed and then you are out of luck because you can't delete them unless and until you kill the processes locking them. If you are in scenario #1 then you can try the delete-directory action from the latest MSBuildCommunityTasks which does have a persist-delete flag (you can read the docs on this one because it's outside the scope of this particular thread) -
progLearner almost 3 yearsThanks, I am out of luck then. The problem is comming from a package dll (Newtonsoft.Json.dll) that sometimes cannot be deleted. Restarting VS fixes the problem, but it is a real pain. -
XDS almost 3 yearsI had a similar problem. There is a process running in the background called VSCompiler.exe or something to that effect. You can try killing this process first before you delete the directory and see if it works (I think it will). Good luck mate! -
progLearner almost 3 yearsActually, did you manage to kill this process from within your .csproj? It would be great if you could share how you did that. Not sure how to do it in an automated way. Ideally, I would make sure to kill it prior to doing a Clean. Cheers -
XDS almost 3 yearsLet us continue this discussion in chat. -
Steve Smith almost 3 yearsThis answer as it is causes problems with .Net Core. The next time you try and compile you'll get the error "Assets file 'c:\whatever\project.assets.json' not found. Run a NuGet package restore to generate this file.". To avoid this, don't add the line to remove the obj folder. -
StayOnTarget over 2 yearsIs there some way to get this included automatically into all CSPROJ files referred to within an entire solution? There is thebefore.solution.sln.targetsfile but its not clear to me how that might help... -
XDS over 2 years@UuDdLrLrSs none that I know of. If you ever come across feel free to point it out. -
Shiv over 1 year@Rolf simply not scalable, not stable, not easily verifiable. Devs would forget to do this all the time and your project files checking by hand a few hundred files? Insanity. Really needs a proper fix. -
ist_lion 8 monthsThis was the best thing I've ever come across - you just saved me so much time