MSBuild in Visual Studio Part 1: Loading and Saving Project Files

One of the questions we get asked on occasion is how well manual changes to project files round trip through Visual Studio. If you invest a ton of effort into manually tweaking your project file with new targets, it really wouldn’t be fun if opening it inside Visual Studio nuked all the changes.

In Visual Studio 2003 and earlier (pre-MSBuild days), the project system would read the project file in and populate a set of internal data structures with the settings and whatnot. When one of those settings changed and then the project was saved, VS would re-write the entire project file with everything. This worked fine back then since there were no customizations in the file. In VS 2005, however, this wouldn’t work very well since we specifically want people to tweak the project file.

How are things different in Visual Studio 2005? Now the project system relies on the MSBuild engine to manipulate the project file. Here’s the sequence of events:

Project System Activity MSBuild API Used
Open a project Project.Load()
Read a property to populate UI, such as particular the properties page and configuration manager Project.EvaluatedProperties
Add/change/remove a property the user set in the UI, or add/change/remove a file Project.SetProperty()
Determine if the project file is dirty Project.IsDirty
Save a project Project.Save()

Within the MSBuild engine, it actually goes and sets the individual pieces of XML directly as necessary, rather than blowing away the file and starting from scratch each time. This means that we preserve any* modifications you’ve made to your project file, such as target additions, includes, and other fun stuff.

Note that as I mentioned earlier, all the APIs the project system uses for this are available in the MSBuild object model. You can get all the details of the object model over at MSDN.

* Except whitespace and wildcards, unfortunately. More on the wildcard issue in a later post.

[ Author: Neil Enns ]

Comments (3)

  1. Glen Gordon (not the MS one) says:

    Does this new behavior also apply to C++ projects since they don’t use MSBuild?

  2. msbuild says:

    No, it doesn’t. All the writings here regarding the inner workings relate to C# and VB projects. Hopefully this will apply to C++ in our next release :)