Javier Marín
Javier Marín

Reputation: 2106

Running MSBuild at runtime

I'm trying to compile my project from an external application that generates two versions of the same project (using compilation constants).

I use this code to execute MsBuild:

string msBuildPath = Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "msbuild.exe");
string projectPath = @"D:\NSM\NSM.csproj";     

var startInfo = new ProcessStartInfo(msBuildPath)
                                {
                                    Arguments = string.Format(@"/t:rebuild /p:Configuration=Release /p:DefineConstants=INTVERSION ""{0}""", projectPath),
                                    WorkingDirectory = Path.GetDirectoryName(msBuildPath),
                                    RedirectStandardOutput = true,
                                    RedirectStandardError = true,
                                    UseShellExecute = false
                                };
Console.WriteLine("> msbuild " + startInfo.Arguments);
var process = Process.Start(startInfo);
Console.Write(process.StandardOutput.ReadToEnd());
process.WaitForExit();

But when I run the program I get this error:

The imported project "C:\Microsoft.CSharp.targets" was not found

How I can solve?

Thanks

Upvotes: 4

Views: 1200

Answers (1)

Andrew Brown
Andrew Brown

Reputation: 4126

If you were to open your NSM.csproj file, you would see a line like this:

<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

The problem is that the $(MSBuildToolsPath) proprety is unset, so your project path becomes \Microsoft.CSharp.targets, which is why you see the error you describe. This isn't a problem when building the project from the Visual Studio IDE or VS Command Prompt, because the appropriate environment that causes this property to get set is set up for you automatically.

So outside of a VS environment, you will need make sure MSBuildToolsPath gets set prior to invoking msbuild. msbuild will pick up set environment variables as properties, so one way of doing this is to set an environment variable by this name prior to starting to msbuild, e.g.:

Environment.SetEnvironmentVariable("MSBuildToolsPath", RuntimeEnvironment.GetRuntimeDirectory());

Upvotes: 3

Related Questions