无法让 Roslyn 与 .NET 5 项目一起工作

Can not get Roslyn to work with .NET 5 project

花了太多时间后,我仍然无法让 Roslyn 加载简单的 C# 项目。 项目来源:

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net5.0</TargetFramework>
    </PropertyGroup>

    <ItemGroup>
      <PackageReference Include="Microsoft.Build" Version="16.11.0" />
      <PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="3.11.0" />
      <PackageReference Include="Microsoft.CodeAnalysis.Workspaces.MSBuild" Version="3.11.0" />
    </ItemGroup>

</Project>

正在尝试加载的代码:

using System;
using Microsoft.CodeAnalysis.MSBuild;

namespace Metrics5
{
    class Program
    {
        static void Main(string[] args)
        {
            using var workspace = MSBuildWorkspace.Create();
            
            workspace.LoadMetadataForReferencedProjects = true;
            var currentProject = workspace.OpenProjectAsync(@"C:\work\Metrics5\Metrics5.csproj").Result;
            var diagnostics = workspace.Diagnostics;
                
            foreach(var diagnostic in diagnostics)
            {
                Console.WriteLine(diagnostic.Message);
            }
        }
    }
}

它说:

Msbuild failed when processing the file 'C:\work\Metrics5\Metrics5.csproj' with message: The SDK 'Microsoft.NET.Sdk' specified could not be found. C:\work\Metrics5\Metrics5.csproj

在我添加 MSBuildSDKsPath 作为环境值后 MSBuildSDKsPath=C:\Program Files\dotnet\sdk.0.301\Sdks 它似乎通过了那一步并卡在了另一步:

Msbuild failed when processing the file 'C:\work\Metrics5\Metrics5.csproj' with message: The imported project "C:\work\Metrics5\bin\Debug\net5.0\Current\Microsoft.Common.props" was not found. Confirm that the expression in the Import de claration "C:\work\Metrics5\bin\Debug\net5.0\Current\Microsoft.Common.props" is correct, and that the file exists on disk. C:\Program Files\dotnet\sdk.0.301\Sdks\Microsoft.NET.Sdk\Sdk\Sdk.props

从这里我不确定如何继续,我是否缺少一些 nuget 包? 我需要额外安装什么吗?

添加对 Microsoft.Build.Locator

的引用

我使用了下一个包:

<ItemGroup>
    <PackageReference Include="Microsoft.Build.Locator" Version="1.4.1" />
    <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.2" PrivateAssets="all" />
    <PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="3.11.0" />
    <PackageReference Include="Microsoft.CodeAnalysis.Workspaces.MSBuild" Version="3.11.0" />
</ItemGroup>

然后使用 MSBuildLocator 注册 MSBuild 实例:

//add this line before using MSBuildWorkspace
MSBuildLocator.RegisterDefaults();  //select the recent SDK
using var workspace = MSBuildWorkspace.Create();

您可以控制 MsBuild 的版本:

var visualStudioInstances = MSBuildLocator.QueryVisualStudioInstances();
//select NET5, or whatever by modifying Version.Major 
var instance = visualStudioInstances.FirstOrDefault(x => x.Version.Major.ToString() == "5");
MSBuildLocator.RegisterInstance(instance);