有没有比从C#/.NET中调用msbuild.exe更好的方式来调用MSBuild?如果有,怎么做?
如果您需要一个针对.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();
}
ToolLocationHelper
类:var toolsetVersion = ToolLocationHelper.CurrentToolsVersion;
var msbuildDir = ToolLocationHelper.GetPathToBuildTools(toolsetVersion);
Microsoft.Build.Utilities.Core
而非Microsoft.Build.Utilities
的ToolLocationHelper
。 - CameronMicrosoft.Build.Engine.Engine
,你会收到一个警告:该类已经被弃用,请改为使用Microsoft.Build.Evaluation.ProjectCollection自Microsoft.Build程序集。
现在,从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) });
}
}
ToolLocationHelper类中没有CurrentToolsVersion可用,我在这里使用V