C# Registry.LocalMachine.OpenSubKey() 返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1268715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Registry.LocalMachine.OpenSubKey() returns null
提问by PositiveGuy
I get a null back from this attempt to access the Windows Registry:
我从这次访问 Windows 注册表的尝试中得到了一个空值:
using (RegistryKey registry = Registry.LocalMachine.OpenSubKey(keyPath))
keyPath is SOFTWARE\\TestKey
关键路径是 SOFTWARE\\TestKey
The key is in the registry, so why is it not finding it under the Local Machine hive?
密钥在注册表中,那么为什么在本地机器配置单元下找不到它呢?
采纳答案by KellCOMnet
In your comment to Dana you said you gave the ASP.NET account access. However, did you verify that that is the account that the site in running under? Impersonate and the anonymous access user can be easy to overlook.
在您对 Dana 的评论中,您说您授予了 ASP.NET 帐户访问权限。但是,您是否验证过该帐户是运行该站点的帐户?冒充和匿名访问用户很容易被忽视。
UNTESTED CODE:
未经测试的代码:
Response.Clear();
Response.Write(Environment.UserDomainName + "\" + Environment.UserName);
Response.End();
回答by Raghav
It can happen if you are on a 64-bit machine. Create a helper class first (requires .NET 4.0 or later):
如果您使用的是 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);
}
}
Usage:
用法:
string keyPath = @"SOFTWARE\MyApp\Settings";
string keyName = "MyAppConnectionStringKey";
object connectionString = RegistryHelpers.GetRegistryValue(keyPath, keyName);
Console.WriteLine(connectionString);
Console.ReadLine();
回答by vapcguy
Just needed to change it from
只需要从
using (RegistryKey registry = Registry.LocalMachine.OpenSubKey(keyPath))
to
到
using (RegistryKey registry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default).OpenSubKey(keyPath))
(Use RegistryKey
instead of Registry
, add the RegistryView
, and put the hive-Local Machine as a method parameter.)
(使用RegistryKey
代替Registry
,添加RegistryView
,并将 hive-Local Machine 作为方法参数。)