Reputation: 8550
After spending way too much time, I still can't make Roslyn to load simple C# project. Project source:
<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>
Code that is trying to load:
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);
}
}
}
}
It says:
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
After I add MSBuildSDKsPath
as environment value MSBuildSDKsPath=C:\Program Files\dotnet\sdk\5.0.301\Sdks
it seems to pass that step and stuck in another:
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\5.0.301\Sdks\Microsoft.NET.Sdk\Sdk\Sdk.props
And from here I'm not sure how to proceed, am I missing some nuget package? Do I need to install additionally something?
Upvotes: 1
Views: 967
Reputation: 11072
Add reference to Microsoft.Build.Locator
I used the next packages:
<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>
Then register the instance of MSBuild using MSBuildLocator:
//add this line before using MSBuildWorkspace
MSBuildLocator.RegisterDefaults(); //select the recent SDK
using var workspace = MSBuildWorkspace.Create();
You Can control the version of 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);
Upvotes: 3