Hack the Build: Cracking MSBuild Project Files

Jomo Fisher -- Here's how you can use the MSBuild Object Model to programmatically access the contents of a project file. This sample console application accepts a single parameter--the full path to some MSBuild project file--and displays all of the assemblies that project references:

using System;

using System.IO;

using Microsoft.Build.BuildEngine;

class MSBuildCracker

{

      const string msbuildBin

            = @"C:\WINDOWS\Microsoft.NET\Framework\v2.0.40607";

      static void Main(string[] args)

      {

            //Load the project.

            Engine engine = new Engine(msbuildBin);

            Project project = new Project(engine);

            project.LoadFromFile(args[0]);

            // Get the references and print them.

            ItemGroup references =

                  project.GetEvaluatedItemsByType("Reference");

            foreach (Item item in references)

            {

                  Console.WriteLine(item.Include);

            }

      }

}

Here's how you would call the tool:

    MSBuildCracker c:\myprojects\project1\project1.csproj

And this is the result:

    System
System.Deployment
System.Drawing
System.Windows.Forms

You can use this technique to access any of the items (like Reference or Compile) or properties (like AssemblyName or Platform).

This posting is provided "AS IS" with no warranties, and confers no rights.