如何在C#中强制向Registry64写入值而非WOW6432Node
问题根源
你虽然在代码中初始化了指向64位注册表视图的root对象,但后续打开子键时使用的是Registry.LocalMachine静态属性,该属性会默认跟随程序运行的平台架构重定向:32位程序运行在64位系统上时,会自动跳转访问WOW6432Node节点,你声明的root对象完全没有被用到,所以写入位置不符合预期。
修复后代码
string[] portal = portalResponse.Split('|'); // 强制访问64位注册表视图 using (var root = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) { // 从64位root对象打开/创建子键,不要用Registry.LocalMachine using (RegistryKey writeKey1 = root.OpenSubKey(@"SOFTWARE\GMS", true) ?? root.CreateSubKey(@"SOFTWARE\GMS")) using (RegistryKey writeKey2 = root.OpenSubKey(@"SOFTWARE\GMS\VCT", true) ?? root.CreateSubKey(@"SOFTWARE\GMS\VCT")) { // 写入值 writeKey1.SetValue("Company Name", portal[0], RegistryValueKind.String); writeKey1.SetValue("Expiration Date", portal[1], RegistryValueKind.String); writeKey1.SetValue("Tech Company", portal[2], RegistryValueKind.String); writeKey1.SetValue("Tech's Name", portal[3], RegistryValueKind.String); writeKey2.SetValue("alerts", portal[4], RegistryValueKind.String); } }
额外注意事项
- 写入
HKEY_LOCAL_MACHINE节点需要程序以管理员权限运行,否则会抛出权限不足异常 - 代码中新增了子键不存在时自动创建的逻辑,避免目标路径不存在时触发空引用报错
- 所有
RegistryKey对象都用using包裹,确保资源自动释放
内容的提问来源于stack exchange,提问作者Lou Smith
相关产品推荐
相关产品推荐

