Tuesday, September 17, 2013

How to build a specific projects from a solution with MSBuild

Sometimes you want to build only a single project, or a list of projects from a solution without building the whole solution with MSBuild.

To do so, you can use custom build targets. You need to add a custom build target for every project you want to build containing the relative path in solution structure of the project (.csproj/.vproj).
Another thing you need to have in mind is that the dots(.) in the project name should be replaced with underscores(_). You can clean or rebuild adding :Clean, :Rebuild at the end of the target.

However if you can check all the MSBuild targets used from the solution. As you may know, when running MSBuild command against a solution file in-memory it is converted to an actual MSBuild project named [SolutionName].sln.metaproj. You can add an environment variable named msbuildemitsolution and set its value to 1 and run MSBuild from command line. Another option is to add /p:msbuildemitsolution=1 to the passed parameters to the build. This will generate the .metaproj file where you can find all the needed targets.

Lets illustrate all the above with a simple example.
Here is a simple project structure:

 
 
 
If we want to build Project.Four and rebuild ProjectTwo we need to call MSBuild with the following arguments:
 
msbuild BuildSpecificProjectsFromASolution.sln /t:"Folder2\Project_Four";"ProjectTwo:Rebuild"

 
You can find the sample solution here.