如何从 C# 调用 MSBuild

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/536539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 07:12:52  来源:igfitidea点击:

How to call MSBuild from C#

c#.netmsbuild

提问by David Schmitt

Is there a better way to call MSBuild from C#/.NET than shelling out to the msbuild.exe? If yes, how?

有没有比从 C#/.NET 调用 MSBuild 更好的方法来调用 msbuild.exe?如果是,如何?

采纳答案by Peter

Yes, add a reference to Microsoft.Build.Engineand use the Engineclass.

是的,添加Microsoft.Build.EngineEngine类的引用并使用它。

PS: Take care to reference the right version. There are 2.0 and 3.5 assemblies and you'll have to make sure that everyone gets the right one.

PS:注意参考正确的版本。有 2.0 和 3.5 程序集,您必须确保每个人都得到正确的程序集

回答by Philippe Monnet

For a .NET 2.0-specific version, you can use the following:

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

回答by crimbo

If you use Microsoft.Build.Engine.Engine, you'll get a warning: This class has been deprecated. Please use Microsoft.Build.Evaluation.ProjectCollection from the Microsoft.Build assembly instead.

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

Now, the proper way to run MSBuild from C# looks like this:

现在,从 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) });
    }

}

回答by Cameron

If all you want is the path to the MSBuild tools folder, you can use the ToolLocationHelperclassfrom the Microsoft.Build.Utilities.Core assembly:

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

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

回答by Aket Gupta

CurrentToolsVersion is not available in ToolLocationHelper class, I am here using V

当前工具版本在 ToolLocationHelper 类中不可用,我在这里使用 V