.net 标准,windows 兼容包和注册表

.net standard, windows compatibility pack and registry

我有一个 .net 标准 2.0 库,我想用它通过 windows 兼容包访问注册表(如果 OS 它的 运行 是 Windows)

if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
     Console.WriteLine("On windows.");
     var dropFolder = Microsoft.Win32.Registry.GetValue(keyName: $@"{userRoot}\{subkey}", valueName: "DropFolder", defaultValue: @"C:\somepath");
     Console.WriteLine($"Drop folder is {dropFolder}");
 }

这会因异常而崩溃

Managed Debugging Assistant 'BindingFailure' : 'The assembly with display name 'Microsoft.Win32.Registry' failed to load in the 'Load' binding context of the AppDomain with ID 1. The cause of the failure was: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Win32.Registry, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.'

我已经将 Windows 兼容性 nuget 包安装到我的 .net 标准项目中。我也试过安装 Microsoft.Win32.Registry nuget 包。

错误仍然存​​在。

如果我注释掉这些行

var dropFolder = Microsoft.Win32.Registry.GetValue(keyName: $@"{userRoot}\{subkey}", valueName: "DropFolder", defaultValue: @"C:\somepath");
Console.WriteLine($"Drop folder is {dropFolder}");

它工作正常。

我正在从 .net 框架库中引用 .net 标准库,所以没有转到 .net 核心的选项。

.dot net 标准 cs 项目

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Windows.Compatibility" Version="2.0.0" />
    <PackageReference Include="MQTTnet" Version="2.8.2" />
    <PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
    <PackageReference Include="RabbitMQ.Client" Version="5.1.0" />
  </ItemGroup>

</Project>

为了将缺少的二进制文件包含在您的 .NET Framework 项目的输出中,您还应该在此项目中安装 Microsoft.Windows.Compatibility 程序包。或者至少安装 Microsoft.Win32.Registry 包。