Missing SDK when using the Microsoft.Build package in .NET Core

August 31, 2018, (updated on September 1, 2018), Software Development

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)

    // TODO: Add code

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

        var process = Process.Start(startInfo);

        var output = process.StandardOutput.ReadToEnd();
        var sdkPaths = Regex.Matches(output, "([0-9]+.[0-9]+.[0-9]+) \\[(.*)\\]")
            .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/RSuter/DNT/Program.cs

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

This site uses Akismet to reduce spam. Learn how your comment data is processed.