【问题标题】:Namespace Microsoft.Win32 could not be found找不到命名空间 Microsoft.Win32
【发布时间】:2018-05-19 03:18:50
【问题描述】:

我昨天安装了 Visual Studio。我想看看Visual Studio安装的是什么版本的.NET Framework,所以我关注了this code from Microsoft。 (向下滚动一下代码)。我用“Console App (.NET Core)”打开了一个新的 Visual C# 项目,并在其中复制了给定的代码。

using System;
using Microsoft.Win32;

public class GetDotNetVersion
{
    public static void Main()
    {
        GetDotNetVersion.Get45PlusFromRegistry();
    }

    private static void Get45PlusFromRegistry()
    {
        const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";

        using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
        {
            if (ndpKey != null && ndpKey.GetValue("Release") != null)
            {
                Console.WriteLine(".NET Framework Version: " + CheckFor45PlusVersion((int)ndpKey.GetValue("Release")));
            }
            else
            {
                Console.WriteLine(".NET Framework Version 4.5 or later is not detected.");
            }
        }
    }

    // Checking the version using >= will enable forward compatibility.
    private static string CheckFor45PlusVersion(int releaseKey)
    {
        if (releaseKey >= 461808)
            return "4.7.2 or later";
        if (releaseKey >= 461308)
            return "4.7.1";
        if (releaseKey >= 460798)
            return "4.7";
        if (releaseKey >= 394802)
            return "4.6.2";
        if (releaseKey >= 394254)
            return "4.6.1";
        if (releaseKey >= 393295)
            return "4.6";
        if (releaseKey >= 379893)
            return "4.5.2";
        if (releaseKey >= 378675)
            return "4.5.1";
        if (releaseKey >= 378389)
            return "4.5";
        // This code should never execute. A non-null release key should mean
        // that 4.5 or later is installed.
        return "No 4.5 or later version detected";
    }
}
// This example displays output like the following:
//       .NET Framework Version: 4.6.1

但是,在编辑器中,“RegistryKey”给出错误:“找不到命名空间。”第二行'使用 Microsoft.Win32;'是灰色的,好像代码中没有调用它一样。

当我查看 Visual Studio 中的解决方案资源管理器面板时,我可以列出依赖项。我没有看到 MicrosoftWin32.dll,但我看到了 mscorlib.dll。我在某处读到 Microsoft.Win32 命名空间可以在那里找到?

有人可以给我一些线索来解决这个问题吗?在哪里可以找到 Microsoft.Win32 命名空间?为什么在这个标准项目中不可用?

【问题讨论】:

  • 该示例针对 .NET Framework 而不是 .NET Core。我不确定核心是否有这个 dll 和命名空间。

标签: c# namespaces


【解决方案1】:

如果你使用netcore,你需要添加包Microsoft.Win32.Registry:

你的项目:

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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Win32.Registry" Version="4.4.0" />
  </ItemGroup>

</Project>

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 2012-07-14
    • 2011-03-10
    • 2017-08-13
    • 2019-08-31
    • 1970-01-01
    相关资源
    最近更新 更多