2009-02-11 27 views
25

¿Existe alguna forma mejor de llamar a MSBuild desde C# /. NET que con un descascaramiento al msbuild.exe? Si es así, ¿cómo?Cómo llamar a MSBuild desde C#

+0

pregunta relacionada (pero usa Powershell en lugar de prima C#) - http://stackoverflow.com/ preguntas/472038/how-to-run-msbuild-from-powershell-without-spawning-msbuild-exe-process/473629 –

Respuesta

16

Para una versión .NET 2.0-específico, puede utilizar lo siguiente:

Engine engine = new Engine(); 
engine.BinPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.System) 
    + @"\..\Microsoft.NET\Framework\v2.0.50727"; 

FileLogger logger = new FileLogger(); 
logger.Parameters = @"logfile=C:\temp\test.msbuild.log"; 
engine.RegisterLogger(logger); 

string[] tasks = new string[] { "MyTask" }; 
BuildPropertyGroup props = new BuildPropertyGroup(); 
props.SetProperty("parm1","hello Build!"); 

try 
{ 
    // Call task MyTask with the parm1 property set 
    bool success = engine.BuildProjectFile(@"C:\temp\test.msbuild",tasks,props); 
} 
catch (Exception ex) 
{ 
    // your error handler 
} 
finally 
{ 
engine.UnregisterAllLoggers(); 
engine.UnloadAllProjects(); 
} 
+0

Para su información, de acuerdo con los documentos, Engine.BinPath está obsoleto. –

1

Si utiliza Microsoft.Build.Engine.Engine, obtendrá una advertencia: This class has been deprecated. Please use Microsoft.Build.Evaluation.ProjectCollection from the Microsoft.Build assembly instead.

Ahora, la forma correcta de ejecutar MSBuild desde C# es el siguiente:

public sealed class MsBuildRunner 
{ 

    public bool Run(FileInfo msbuildFile, string[] targets = null, IDictionary<string, string> properties = null, LoggerVerbosity loggerVerbosity = LoggerVerbosity.Detailed) 
    { 
     if (!msbuildFile.Exists) throw new ArgumentException("msbuildFile does not exist"); 

     if (targets == null) 
     { 
      targets = new string[] {}; 
     } 
     if (properties == null) 
     { 
      properties = new Dictionary<string, string>(); 
     } 

     Console.Out.WriteLine("Running {0} targets: {1} properties: {2}, cwd: {3}", 
           msbuildFile.FullName, 
           string.Join(",", targets), 
           string.Join(",", properties), 
           Environment.CurrentDirectory); 
     var project = new Project(msbuildFile.FullName, properties, "4.0"); 
     return project.Build(targets, new ILogger[] { new ConsoleLogger(loggerVerbosity) }); 
    } 

} 
1

Si lo que quieres es la ruta de la carpeta de herramientas de MSBuild, puede utilizar la ToolLocationHelper class del Microsoft.B Asamblea uild.Utilities.Core:

var toolsetVersion = ToolLocationHelper.CurrentToolsVersion; 
var msbuildDir = ToolLocationHelper.GetPathToBuildTools(toolsetVersion); 
0

CurrentToolsVersion no está disponible en la clase ToolLocationHelper, estoy aquí usando V