首页 > 解决方案 > RegistryKey 更改为新的 csproj 格式

问题描述

对于我们的一个项目,我更改了 csproj 格式,以便为 .net Core 迁移做准备。目前我们使用的是 .net Framework 4.8。

我没有更改代码中的任何内容,但后来发生了错误,应用程序无法再找到注册表项。两次应用程序都是在同一台 64 位机器上使用 AnyCPU 调试构建的。

string registry_key32 = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
{
    var subKeys = key.GetSubKeyNames();
}

这会在更改前返回约 400 个键,之后仅返回约 200 个。

为什么从旧的 csproj 格式转移到新的格式时,此方法调用的结果会发生变化?

标签: c#registrycsproj

解决方案


我不能告诉你它为什么会改变,但似乎 .net 核心编译规则与新的 csproj 格式一起使用。因此,当您从 .net Framework 迁移到 .net Core 时,也会出现此问题,就像在此处搜索注册表项在 .net core 和 .net 框架中给出不同的输出一样

为“x86”编译:

Always 32-bit
On 32-bit platforms, accesses 32-bit registry
On 64-bit platforms, accesses 32-bit registry (inside Wow6432Node)

为“x64”编译:

Always 64 bit
On 32-bit platforms, won't run
On 64-bit platforms, accesses 64-bit registry (not inside Wow6432Node)

为“AnyCpu”编译的 .NET 应用程序

Either 32 or 64 bit depending on platform
On 32-bit platforms, accesses 32-bit registry
On 64-bit platforms, accesses 64-bit registry (not inside Wow6432Node)

长话短说,解决方案也是硬编码检查 64 位注册表项。

string registry_key32 = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
{
    var subKeys = key.GetSubKeyNames();
}

string registry_key64 = @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
{
    var subKeys = key.GetSubKeyNames();
}

推荐阅读