I am attempting to build a tool (using C# and .NET 7.0, Visual Studio 2022) that will analyze another C# project. I added the MSBuild.Locator
package and invoked it with MSBuildLocator.RegisterDefaults()
. However, when I attempt to actually open the project to be analyzed, I get the following error:
Here is the source code of the tool:
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.Text;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
namespace AnalysisTool
{
class Program
{
public static async Task DoActualWork()
{
var workspace = MSBuildWorkspace.Create();
workspace.LoadMetadataForReferencedProjects = true;
workspace.WorkspaceFailed += OnWorkspaceFailed;
// Error occurs here
var project = await workspace.OpenProjectAsync(
@"C:\Path\To\OtherProject.csproj");
var compilation = await project.GetCompilationAsync();
}
public static async Task Main(string[] args)
{
var vsAvail = MSBuildLocator.QueryVisualStudioInstances().ToList();
MSBuildLocator.RegisterDefaults();
await DoActualWork();
}
private static void OnWorkspaceFailed(object sender,Microsoft.CodeAnalysis.WorkspaceDiagnosticEventArgs e)
{
if (e.Diagnostic.Kind == Microsoft.CodeAnalysis.WorkspaceDiagnosticKind.Failure)
{
Console.WriteLine(e.Diagnostic.ToString());
}
}
}
}
And the analysis tool's associated project file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<RollForward>Major</RollForward>
<OutDir>..\Bin\</OutDir>
<OutputPath>$(OutDir)</OutputPath>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Build.Locator" Version="1.5.5" />
<PackageReference Include="Microsoft.CodeAnalysis" Version="4.4.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Features" Version="4.4.0" />
<PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.Features" Version="4.4.0" />
<PackageReference Include="Microsoft.CodeAnalysis.Workspaces.MSBuild" Version="4.4.0" />
<PackageReference Include="NuGet.ProjectModel" Version="6.4.0" />
</ItemGroup>
</Project>
I've tried walking it back to .NET 5.0, with the same error. I'd appreciate any help.