Running MSBuild at runtime

I am 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:

Could not find imported project "C: \ Microsoft.CSharp.targets"

How can i decide?

thanks

+4
source share
1 answer

If you open your NSM.csproj file, you will see a line like this:

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

The problem is that $(MSBuildToolsPath) proprety is not installed, so your project path becomes \Microsoft.CSharp.targets , so you see the error you described. This is not a problem when creating a project from the Visual Studio IDE or VS Command Prompt, because the appropriate environment that invokes this property will be automatically configured for you.

Therefore, outside of the VS environment, you need to make sure that MSBuildToolsPath installed before msbuild . msbuild will display the specified environment variables as properties, so one way to do this is to set the environment variable by that name before msbuild , for example:

 Environment.SetEnvironmentVariable("MSBuildToolsPath", RuntimeEnvironment.GetRuntimeDirectory()); 
+3
source

Source: https://habr.com/ru/post/1340811/


All Articles