How can I find the version of .NET run-time programmatically?

前端 未结 2 1662
情书的邮戳
情书的邮戳 2021-02-05 06:48

I need a solution to give me the .NET run-time version of both the full framework as well as the .NET Core.

On a machine with the following .NET

2条回答
  •  暖寄归人
    2021-02-05 07:42

    There isn't a unified way to do this yet, although there is an open request for this here that you can track. If you click through the various issues that reference that discussion and the issues referenced further downstream, you'll see there are also some bugs in some implementations right now, but there is active work (one of the issues had a related check-in just 8 hours ago).

    For .NET Framework:

    using System;
    ...
    string ver = AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName;
    

    and for .NET Core:

    using System.Reflection;
    using System.Runtime.Versioning;
    ...
    string ver = Assembly.GetEntryAssembly()?.GetCustomAttribute()?.FrameworkName;
    

    Output:

    .NETFramework,Version=v4.5.1
    .NETCoreApp,Version=v2.0
    

    Obviously these are a bit of a hassle to use programmatically, hence the requests for a better API (including this open issue from Microsoft discussing a new API specifically focused on testing for a minimum target framework).

    The other piece of the puzzle that will probably always be impossible is that a given application can reference many targets. Under the hood you might be pulling in .NET Standard 2.x and .NET Standard 1.x libraries, for example. I doubt there will ever be a good way to get a complete picture of all the targets behind a given collection of executing assemblies...

提交回复
热议问题