none
Create project programmatically with MSBuild 4.0

    Question

  • Hi,

    It used to be pretty easy creating project files with MSBuild 3.5, e.g.

     

    using Microsoft.Build.BuildEngine;
    using System.Runtime.InteropServices;
    
    Microsoft.Build.BuildEngine.Project testProj = new Microsoft.Build.BuildEngine.Project(new Engine(@"C:\Windows\Microsoft.Net\Framework\v3.5\MSBuild.exe"));
    Target buildTarget = testProj.Targets.AddNewTarget("BuildProjects");
    BuildTask msBuildTask = buildTarget.AddNewTask("MSBuild");
    testProj.Save(@"C:\testProj.proj");

    Now that Microsoft.Build.BuildEngine namespace is deprecated I can't figure out how to proceed. I can create an empty project as follows:

    using Microsoft.Build.Evaluation;
    using Microsoft.Build.Construction;
    using Microsoft.Build.Execution;
    
    Project testProj = new Project();
    
    // How to add targets and tasks???
    
    testProj.Save(@"C:\testProj.proj");

     

    But I don't know how to set additional project elements, custom targets, etc.. Can you provide any suggestions, pointers, resources with code samples? There doesn't seem to be any code samples at all on MSDN.

     

    Thanks,

    Vladimir Nestoyanov

     

    Monday, August 23, 2010 8:26 PM

Answers

  • Unfortunately there is still very little / no documentation that I can find which covers this new API appropriately. I'll see if I can get some help from the MSBuild team and start an API Hands-On section here. http://code.msdn.microsoft.com/msbuildho

    In the mean time, below is a sample which does what you want. I am highly suspicious that there is a better way to achieve it though.

     

     using Microsoft.Build.Construction;
     using Microsoft.Build.Evaluation;
     using System.Linq;
    
     class Program
     {
      static void Main(string[] args)
      {
       Project testProj = new Project();
       testProj.Xml.AddTarget("BuildProjects");
    
       foreach (ProjectTargetElement pti in testProj.Xml.Targets.Where(pti => pti.Name == "BuildProjects"))
       {
        pti.AddTask("MSBuild");   
       }
       
       testProj.Save(@"C:\testProj.proj");
    
      }
     }
    


    Visual Studio ALM MVP
    My Blog | MSBuild Extension Pack | MSBuild Explorer
    Tuesday, August 24, 2010 9:39 AM