.Net Framework / Standard Access Registry

时间:2018-02-20 22:53:26

标签: .net registry .net-standard

我有以下情况,其中注册表访问不适用于.Net Standard 2.0 dll。该程序分为两部分......

  1. .Net Standard 2.0的共享库。它引用了Microsoft.Win32.Registry nuget包(v4.4)。共享库中包含以下方法:

    public static void GetRegistryValue()
    {
        // it does successfully enter this if statment
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            var y = Microsoft.Win32.Registry.LocalMachine;  // this returns null
            var x = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Default); // this throws System.PlatformNotSupportedException: 'Registry is not supported on this platform.'
        }
    }
    
  2. 一个完整的.Net Framework主应用程序。我试过.4.6.1和.4.7.1。主应用程序引用共享库。当主应用程序调用GetRegistryValue()时,它不起作用。

  3. Microsoft.Win32.Registry.LocalMachine返回null,因此无效。

    RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine,RegistryView.Default)抛出System.PlatformNotSupportedException。

    我在这里做错了什么?

1 个答案:

答案 0 :(得分:-1)

这是设计的。不要将此类仅依赖于Windows的依赖项添加到.NET Standard类库中。在编译时,它只会误导MSBuild / NuGet选择一个错误的程序集(返回null或抛出PlatformNotSupportedException你看到的内容。

此类引用必须仅存在于.NET Framework项目中,并且关于如何将引用和相关代码库移动到上层,您必须自己考虑和重构。答案太广了。

相关问题