我从这次访问Windows注册表的尝试中得到了一个null:
using (RegistryKey registry = Registry.LocalMachine.OpenSubKey(keyPath))
keyPath是SOFTWARE\\TestKey
密钥在注册表中,为什么它不能在Local Machine配置单元中找到它?
答案 0 :(得分:58)
如果您使用的是64位计算机,则可能会发生这种情况。首先创建一个帮助器类(需要.NET 4.0或更高版本):
public class RegistryHelpers
{
public static RegistryKey GetRegistryKey()
{
return GetRegistryKey(null);
}
public static RegistryKey GetRegistryKey(string keyPath)
{
RegistryKey localMachineRegistry
= RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
Environment.Is64BitOperatingSystem
? RegistryView.Registry64
: RegistryView.Registry32);
return string.IsNullOrEmpty(keyPath)
? localMachineRegistry
: localMachineRegistry.OpenSubKey(keyPath);
}
public static object GetRegistryValue(string keyPath, string keyName)
{
RegistryKey registry = GetRegistryKey(keyPath);
return registry.GetValue(keyName);
}
}
用法:
string keyPath = @"SOFTWARE\MyApp\Settings";
string keyName = "MyAppConnectionStringKey";
object connectionString = RegistryHelpers.GetRegistryValue(keyPath, keyName);
Console.WriteLine(connectionString);
Console.ReadLine();
答案 1 :(得分:2)
在您对Dana的评论中,您说您已授予ASP.NET帐户访问权限。但是,您确认这是该网站运行的帐户吗? Impersonate和匿名访问用户很容易被忽视。
未经审查的代码:
Response.Clear();
Response.Write(Environment.UserDomainName + "\\" + Environment.UserName);
Response.End();
答案 2 :(得分:0)
只需将其从
进行更改using (RegistryKey registry = Registry.LocalMachine.OpenSubKey(keyPath))
到
using (RegistryKey registry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default).OpenSubKey(keyPath))
(使用RegistryKey
代替Registry
,添加RegistryView
,然后将hive-Local Machine用作方法参数。)