C# Registry.GetValue()适用于Web应用程序,但不适用于控制台应用程序
下面的代码完美地用于十多个intranet Web应用程序中C# Registry.GetValue()适用于Web应用程序,但不适用于控制台应用程序,c#,winapi,registry,console-application,C#,Winapi,Registry,Console Application,下面的代码完美地用于十多个intranet Web应用程序中 public static string dbConnectionStringAIMS = RegRead(@"HKEY_LOCAL_MACHINE\SOFTWARE\MNI_APPS", "sql.connection.aims"); public static string dbConnectionStringDYN = RegRead(@"HKEY_LOCAL_MACHINE\SOFTWARE\MNI_APPS", "sql.c
public static string dbConnectionStringAIMS = RegRead(@"HKEY_LOCAL_MACHINE\SOFTWARE\MNI_APPS", "sql.connection.aims");
public static string dbConnectionStringDYN = RegRead(@"HKEY_LOCAL_MACHINE\SOFTWARE\MNI_APPS", "sql.connection.dynamics");
public static string RegRead(string keyName, string valueName) {
string retVal = Convert.ToString(Registry.GetValue(keyName, valueName, ""));
return retVal;
}
但当我将其剪切并粘贴到Windows控制台应用程序中时,它构建得很干净,运行时不会崩溃,但总是返回null。注册表项如图所示存在,如前所述,此代码是使用这些相同的键从工作的Web应用程序中删除的
我能想到的观察结果和差异:
Web应用程序运行在Web服务器上,在Active Directory服务帐户下运行的应用程序池中的http上下文中
此控制台应用程序可能是在我自己的凭据下在我的桌面上运行的
我的本地注册表具有与web服务器完全相同的HKLM项和值
其他SO文章中似乎有不同的语法,建议先使用Registry.LocalMachine.OpenSubKey,然后使用.GetValue。所以
它也返回null
有什么想法吗
谢谢 这终于奏效了:
public static string dbConnectionStringAIMS = RegRead(@"SOFTWARE\OMNI_APPS", "sql.connection.aims");
public static string dbConnectionStringDYN = RegRead(@"SOFTWARE\OMNI_APPS", "sql.connection.dynamics");
public static string RegRead(string keyName, string valueName) {
string retVal;
RegistryKey key = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
key = key.OpenSubKey(keyName, true);
retVal = (string)key.GetValue(valueName);
return retVal;
}
我阅读了其他SO文章,指出了32位操作系统注册表和64位操作系统注册表的区别,并发现以下代码:
请注意,正如您所知,代码是静态类的一部分-开始时查找错误代码您是否排除了作为观察到的行为的可能原因?有人将该问题标记为我在下面的答案中引用的资源的副本。LOL.S.O.社区反应很快,而且通常都很到位-
public static string dbConnectionStringAIMS = RegRead(@"SOFTWARE\OMNI_APPS", "sql.connection.aims");
public static string dbConnectionStringDYN = RegRead(@"SOFTWARE\OMNI_APPS", "sql.connection.dynamics");
public static string RegRead(string keyName, string valueName) {
string retVal;
RegistryKey key = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
key = key.OpenSubKey(keyName, true);
retVal = (string)key.GetValue(valueName);
return retVal;
}