Registry.GetValue始终返回null
我的注册表中有以下密钥:
在: HKEY_LOCAL_MACHINE\SOFTWARE\RSA
我有值对象调用 – WebExControlManagerPath
,其值为c:\
我想这样做:
var r = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\RSA", "WebExControlManagerPth",null); if(r!=null) ProcessAsUser.Launch(ToString());
但r
值始终为null。
有任何想法吗?
您不像在批处理脚本中那样访问HKEY_LOCAL_MACHINE配置单元,就像在C#中一样。 你调用Registry.LocalMachine
,如下:
RegistryKey myKey = Registry.LocalMachine.OpenSubKey( @"Software\RSA", false); String value = (String)myKey.GetValue("WebExControlManagerPth"); if (!String.IsNullOrEmpty(value)) { ProcessAsUser.Launch(ToString()); }
更新:
如果返回null,请将构建体系结构设置为Any CPU 。 操作系统可能以不同方式虚拟化32位和64位注册表。 请参阅: http : //msdn.microsoft.com/en-us/library/windows/desktop/aa965884%28v=vs.85%29.aspx , 从32位应用程序读取64位注册表 ,以及http://msdn.microsoft .com / zh-CN / library / windows / desktop / ms724072%28v = vs.85%29.aspx 。
杰森的陈述是对的,操作系统是问题,下面的代码将帮助您解决。
RegistryKey localKey; if(Environment.Is64BitOperatingSystem) localKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); else localKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32); string value = localKey.OpenSubKey("RSA").GetValue("WebExControlManagerPth").ToString();
如果您使用的是64位操作系统,当您尝试获取HKEY_LOCAL_MACHINE\SOFTWARE\RSA
它实际上是在寻找HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\RSA
,这就是为什么您获得null
使用regedt32.exe查看注册表项的安全权限; 检查您是否以管理员身份运行并关闭了UAC。 根据opensubkey文档,在访问任何密钥之前需要先打开它; http://msdn.microsoft.com/en-us/library/z9f66s0a.aspx
我在路径的开头有额外的“\”,确保设置正确。
这里没有任何解决方案适用于我,我仍然从我的注册表读取返回null。 基于上述答案的合并,我终于找到了一个对我有用的解决方案。 感谢所有人指出我正确的方向。
我很欣赏我迟到了,但我认为如果上述解决方案对他们不起作用,这可能对其他人有所帮助。
该函数是类的一部分:
/// /// Gets the specified setting name. /// /// Name of the setting. /// Returns Setting if the read was successful otherwise, "undefined". public static string get(string settingName) { RegistryKey key; if (Environment.Is64BitOperatingSystem) key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\MyCompany\MyProductName", false); else key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\MyCompany\MyProductName", false); try { String value = (String)key.GetValue(settingName); return value; } catch { // Null is not returned as in this case, it is a valid value. return "undefined"; } finally { key.Close(); } }