Registry.LocalMachine.OpenSubKey()返回null

我从这次访问Windows注册表的尝试中获得了null:

using (RegistryKey registry = Registry.LocalMachine.OpenSubKey(keyPath)) 

keyPath是SOFTWARE\\TestKey

关键是在注册表中,为什么它不在Local Machine配置单元下找到它?

在您对Dana的评论中,您说您已授予ASP.NET帐户访问权限。 但是,您确认这是该网站运行的帐户吗? Impersonate和匿名访问用户很容易被忽视。

未经编码的代码:

 Response.Clear(); Response.Write(Environment.UserDomainName + "\\" + Environment.UserName); Response.End(); 

如果您使用的是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();