How MSBuild Clean Works


Beta 2 and Beyond

Clean happens at three different times,
  1. Explicit Clean. The user explicitly selected BuildàClean menu item. In this case, we attempt to remove all files produced by prior builds.
  2. Rebuild. The user selected BuildàRebuild menu item. Rebuild is simply a Clean followed by a regular Build.
  3. Incremental Clean. The user just builds the project. In this case, we try to remove obsolete build outputs. For example, a prior build produced .PDB files but the current build doesn’t because the user has changed project settings.

In all cases, a specific set of rules always applies,
* Cleaning a project cleans referenced projects too.
* Clean only deletes files in the current obj and bin folders.
* Clean only deletes copy local references if they are in the project cone.
* Clean skips locked and inaccessible files, but issues a warning.
* Every file produced by build is remembered until it is deleted by Clean.
* After a successful build, obsolete build outputs are removed as if Clean had been called first.
* After a failed build no build outputs are removed.

Extending the Visual Studio Clean System

The rules for clean are in the file Microsoft.Common.Targets. If you use or extend this targets file and you want the files produced by your build targets to be cleaned up too then you need to add your files produced to one of two item lists:
* FileWrites – this is the most common case.
* FileWritesShareable – use this for files that shouldn’t be removed when dealing with a common bin directory. (This is to support rule 3 for CopyLocal references)

As long as you get them into one of those buckets they will be cleaned appropriately. The main gotcha here is that you want to make sure you populate these on both clean as well as incremental builds. So if for example your target skips because inputs are up to date wrt outputs you still need to report FileWrites. In some cases this implies authoring new targets that keep track of writes for you independently of actually doing the step. Our compiler targets are one such example which you can use to model this from. If you don’t get this right then your build outputs likely will be removed by Incremental Clean.
Microsoft Communities