有没有更好的方法从C#/ .NET调用MSBuild而不是shelling到msbuild.exe?如果有,怎么样?
是的,添加Microsoft.Build.Engine
对Engine类的引用并使用它.
PS:注意参考正确的版本.有2.0和3.5个程序集,你必须确保每个人都得到正确的程序集.
对于特定于.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(); }