Rico Suter's blog.
 


When I tried to use the Microsoft.Build package in my DNT CLI to read .NET .csproj files in a .NET Core app, I got the following error:

Microsoft.Build.Exceptions.InvalidProjectFileException: The SDK 'Microsoft.NET.Sdk' specified could not be found. 
   at Microsoft.Build.Shared.ProjectErrorUtilities.ThrowInvalidProject(String errorSubCategoryResourceName, IElementLocation elementLocation, String resourceName, Object[] args)
   at Microsoft.Build.Evaluation.Evaluator`4.ExpandAndLoadImportsFromUnescapedImportExpressionConditioned(String directoryOfImportingFile,     

It seems that the problem can be fixed by manually setting the MSBUILD_EXE_PATH environment variable. I wrote a simple method which loads the latest installed binary and sets the variable:

static void Main(string[] args)
{
    SetMsBuildExePath();

    // TODO: Add code
}

private static void SetMsBuildExePath()
{
    try
    {
        var startInfo = new ProcessStartInfo("dotnet", "--list-sdks") 
        { 
            RedirectStandardOutput = true }
        };

        var process = Process.Start(startInfo);
        process.WaitForExit(1000);

        var output = process.StandardOutput.ReadToEnd();
        var sdkPaths = Regex.Matches(output, "([0-9]+.[0-9]+.[0-9]+) \\[(.*)\\]")
            .OfType<Match>()
            .Select(m => System.IO.Path.Combine(m.Groups[2].Value, m.Groups[1].Value, "MSBuild.dll"));

        var sdkPath = sdkPaths.Last();
        Environment.SetEnvironmentVariable("MSBUILD_EXE_PATH", sdkPath);
    }
    catch (Exception exception)
    {
        ConsoleUtilities.Write("Could not set MSBUILD_EXE_PATH: " + exception);
    }
}

The actual implementation and usage can be found here: github.com/RicoSuter/DNT/Program.cs



Discussion