开发者

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


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());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜