我尝试在 c# 中使用 Microsoft.Win32.RegistryKey 插入一些简单的注册表项,但路径会自动更改为:
HKEY_LOCAL_MACHINE\SOFTWARE\Test
到
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Test
我尝试过谷歌,但只得到一些模糊且令人困惑的结果。以前有人处理过这个问题吗?一些示例代码将非常感激。
可以使用RegistryKey.OpenBaseKey来解决这个问题:
using var baseReg = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
using var reg = baseReg.CreateSubKey("Software\\Test");
在 WOW64 下,某些注册表项会被重定向(软件)。当 32 位或 64 位应用程序对重定向密钥进行注册表调用时,注册表重定向程序会拦截该调用并将其映射到该密钥相应的物理注册表位置。有关更多信息,请参阅注册表重定向器。
您可以使用 RegistryKey.OpenBaseKey Method 上的 RegistryView Enumeration 显式打开 32 位视图并直接访问 HKLM\Software\。
我不知道如何使用 .reg 文件解决它。但只能在BAT文件中,如下:
您必须在命令行末尾添加
/reg:64
。
例如:
REG ADD "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\Background" /v "OEMBackground" /t REG_DWORD /d 0x00000001 /f /reg:64
这是我开发的工作代码,只能读取和写入 32 位注册表。它适用于 32 位和 64 位应用程序。如果未设置该值,“read”调用会更新注册表,但如何删除它是非常明显的。它需要 .Net 4.0,并使用 OpenBaseKey/OpenSubKey 方法。
我目前使用它来允许 64 位后台服务和 32 位托盘应用程序无缝访问相同的注册表项。
using Microsoft.Win32;
namespace SimpleSettings
{
public class Settings
{
private static string RegistrySubKey = @"SOFTWARE\BlahCompany\BlahApp";
public static void write(string setting, string value)
{
using (RegistryKey registryView = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
using (RegistryKey registryCreate = registryView.CreateSubKey(RegistrySubKey))
using (RegistryKey registryKey = registryView.OpenSubKey(RegistrySubKey, true))
{
registryKey.SetValue(setting, value, RegistryValueKind.String);
}
}
public static string read(string setting, string def)
{
string output = string.Empty;
using (RegistryKey registryView = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
using (RegistryKey registryCreate = registryView.CreateSubKey(RegistrySubKey))
using (RegistryKey registryKey = registryView.OpenSubKey(RegistrySubKey, false))
{
// Read the registry, but if it is blank, update the registry and return the default.
output = (string)registryKey.GetValue(setting, string.Empty);
if (string.IsNullOrWhiteSpace(output))
{
output = def;
write(setting, def);
}
}
return output;
}
}
}
用途: 将其放入它自己的类文件 (.cs) 中并这样调用它:
using SimpleSettings;
string mysetting = Settings.read("SETTINGNAME","DEFAULTVALUE");