如何确定是否安装了 .Net 5 运行时?

问题描述:

我安装了 .NET 5.0 预览版 SDK 和运行时.

I installed .NET 5.0 preview SDK and runtime.

如何检测/确定 .Net 5 运行时是否安装在 C# 中?

How do I detect/determine if the .Net 5 runtime is installed from in C# ?

这里有一些错误:

  1. .NET 5 不是 .NET Framework 的一个版本,它是 .NET Core 的下一个版本(来源)
  2. 如果您的应用程序是针对 .NET 5 编译的,而您尝试运行的计算机没有安装 .NET 5,那么您的应用程序将无法启动(将其想象为尝试运行编译的应用程序对于仅安装了 .NET Framework 3.5 的计算机上的 .NET Framework 4.8)*
  1. .NET 5 is not a version of .NET Framework, it is the next version of .NET Core (source)
  2. If your app is compiled against .NET 5, and the computer you're trying to run on does not have .NET 5 installed, then your app simply won't launch (think of it like trying to run an application compiled for .NET Framework 4.8 on a computer which only has .NET Framework 3.5 installed)*

由于 .NET 5 是 .NET Core 的下一个版本,您可以轻松使用新的(在 Core 3.0 中)API

And as .NET 5 is the next version of .NET Core, you can easily use the new (in Core 3.0) APIs

var netVersion = System.Environment.Version;
var runtimeVer = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription;

正如您在原始问题中提到的,您正在阅读用于获取 .NET Framework 版本的注册表项(我假设是 so).那么指定安装的 .NET Core 版本的密钥的位置位于不同的位置,即 HKEY_LOCAL_MACHINESOFTWAREdotnetSetupInstalledVersions.您可以通过以下方式阅读它们:

As mentioned in your original question, you are reading the registry keys for getting the .NET Framework versions (I'm assuming à la so). Well the location for the keys that specify the .NET Core versions installed are located in a different place, namely HKEY_LOCAL_MACHINESOFTWAREdotnetSetupInstalledVersions. Here is how you could read them:

const string subkey = @"SOFTWAREdotnetSetupInstalledVersions";
var baseKey = Registry.LocalMachine.OpenSubKey(subkey);
if (baseKey.SubKeyCount == 0)
    return;

foreach (var platformKey in baseKey.GetSubKeyNames())
{
    using (var platform = baseKey.OpenSubKey(platformKey))
    {
        Console.WriteLine($"Platform: {platform.Name.Substring(platform.Name.LastIndexOf("\") + 1)}");
        if (platform.SubKeyCount == 0)
            continue;

        var sharedHost = platform.OpenSubKey("sharedhost");
        foreach (var version in sharedHost.GetValueNames())
            Console.WriteLine("{0,-8}: {1}", version, sharedHost.GetValue(version));
    }
}


* 预计如果您使用 self-contained 编译您的应用程序,它会将运行时与您的应用程序捆绑在一起


* Expect if you compile your application with self-contained which will bundle the runtime together with your app