代码之家  ›  专栏  ›  技术社区  ›  David Schmitt

如何从C调用MSBuild#

  •  25
  • David Schmitt  · 技术社区  · 16 年前

    从C#/.NET调用MSBuild是否有比直接调用MSBuild.exe更好的方法?如果是,如何进行?

    5 回复  |  直到 16 年前
        1
  •  28
  •   David Schmitt    16 年前

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

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

        2
  •  16
  •   David Schmitt    15 年前

    对于特定于.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();
    }
    
        3
  •  1
  •   crimbo    10 年前

    如果你使用 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) });
        }
    
    }
    
        4
  •  1
  •   Cameron    8 年前

    如果只需要指向MSBuild tools文件夹的路径,则可以使用 ToolLocationHelper class

    var toolsetVersion = ToolLocationHelper.CurrentToolsVersion;
    var msbuildDir = ToolLocationHelper.GetPathToBuildTools(toolsetVersion);
    
        5
  •  0
  •   Aket Gupta    8 年前

    CurrentToolsVersion在ToolLocationHelper类中不可用,我在这里使用的是V