How to get the Target Framework/s of a project (.csproj) using Microsoft.CodeAnalysis (or similar)?

1k Views Asked by At

I'm building a .NET tool that needs to query project properties like Target Framework/s. My first thought has been Microsoft.CodeAnalysis.

using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis.MSBuild;

public static class Program
{
    public static async Task Main()
    {
        MSBuildLocator.RegisterDefaults(); 
        using var workspace = MSBuildWorkspace.Create();
        var pr = await workspace.OpenProjectAsync("E:\\Repos\\SuperJMN\\DotNet-Ssh-Deployer\\NetCoreSsh\\DotNetSsh.csproj");
    }
}

I've loaded a project, and I can see a lot of information in the pr instance, but I haven't found anything related to the TFMs.

1

There are 1 best solutions below

3
Chobo On

You can leverage reflection's Assembly.ImageRuntimeVersion property to grab it.

Here's the documentation on it: https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.imageruntimeversion?redirectedfrom=MSDN&view=net-6.0#System_Reflection_Assembly_ImageRuntimeVersion