如何从C#调用MSBuild

时间:2009-02-11 12:21:14

标签: c# .net msbuild

有没有更好的方法从C#/ .NET调用MSBuild而不是shelling到msbuild.exe?如果是,怎么样?

5 个答案:

答案 0 :(得分:28)

是的,添加对Microsoft.Build.Engine的引用并使用Engine类。

PS:注意参考正确的版本。有2.0和3.5个程序集,您必须make sure that everyone gets the right one

答案 1 :(得分:16)

对于特定于.NET 2.0的版本,您可以使用以下命令:

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();
}

答案 2 :(得分:1)

如果您使用Microsoft.Build.Engine.Engine,则会收到警告:This class has been deprecated. Please use Microsoft.Build.Evaluation.ProjectCollection from the Microsoft.Build assembly instead.

现在,从C#运行MSBuild的正确方法如下:

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) });
    }

}

答案 3 :(得分:1)

如果你想要的只是MSBuild工具文件夹的路径,你可以使用Microsoft.Build.Utilities.Core程序集中的ToolLocationHelper class

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

答案 4 :(得分:0)

CurrentLoolsVersion在ToolLocationHelper类中不可用,我在这里使用V