tags:

views:

1887

answers:

2

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

+14  A: 

Yes, add a reference to Microsoft.Build.Engine and use the Engine class.

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.

Petoj
+5  A: 

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

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