Partager via


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.

Comments

  • Anonymous
    February 18, 2005
    Some interesting stuff in this. Trying some stuff with this to write changes to an existing project file, but the object model seems to be missing OutputItems (or a way of attaching them to TaskElements).
    Is this just a 'work in progress' type issue that'll be addressed in later betas?
    Thanks for these articles by the way.
  • Anonymous
    February 23, 2005
    Rob, I'm pretty sure this won't be in Beta2. Hopefully, this is something we can get into the RC. The current plan is that these APIs will not cover everything that the MSBuild language can express (as you've discovered).

    This posting is provided "AS IS" with no warranties, and confers no rights.
  • Anonymous
    March 02, 2005
    Hi is it possible to get from a solution file also what all project it builds and project interdependencies?
  • Anonymous
    March 02, 2005
    The comment has been removed
  • Anonymous
    January 19, 2007
    I am not able to get the exact Full Path of the referenced assemblies everytime. I tried reading FullPath Metadata of the Item but it seems not to work everytime. What is the appropriate way to get this? Thank you, Nush