从注册表中读取值
Posted
技术标签:
【中文标题】从注册表中读取值【英文标题】:Reading value from registry 【发布时间】:2012-10-23 12:52:05 【问题描述】:谷歌今天没有帮助我,所以我需要你的帮助。有没有可能的方法?例如这个位置 --> HKEY_LOCAL_MACHINE > SOFTWARE > MyKey 该列是测试键
【问题讨论】:
您查看过 Microsoft.Win32.RegistryKey 的文档吗? 我决定帮助您使用 Google-Fu - 它可能需要一些改进。 google.com/search?q=read+registry+values+csharp 您需要 15 rep 来支持/反对投票。 【参考方案1】:64 位 + 32 位
using Microsoft.Win32;
public static string GetRegistry()
string registryValue = string.Empty;
RegistryKey localKey = null;
if (Environment.Is64BitOperatingSystem)
localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
else
localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry32);
try
localKey = localKey.OpenSubKey(@"Software\\MyKey");
registryValue = localKey.GetValue("TestKey").ToString();
catch (NullReferenceException nre)
return registryValue;
【讨论】:
很高兴你给出了如此完整的答案——我个人会稍微重构一下,因为受if
影响的唯一代码是RegistryView.Registry32
/64
的值。
我同意 Puzey 先生的观点。此外,如果注册表中不存在“MyKey”,或者由于其他原因读取失败,则 localKey 将为空,您将收到异常。此处应使用 try/catch 语句。【参考方案2】:
代码项目中的示例:
Read, write and delete from registry with C#
All (you wanted to know) about the Registry with C#, Part 1 of 2
using Microsoft.Win32;
...
RegistryKey masterKey = Registry.LocalMachine.CreateSubKey(
"SOFTWARE\\Test\\Preferences");
if (masterKey == null)
Console.WriteLine ("Null Masterkey!");
else
Console.WriteLine ("MyKey = 0", masterKey.GetValue ("MyKey"));
masterKey.Close();
【讨论】:
【参考方案3】:试试这个:
static object GetRegistryValue(string fullPath, object defaultValue)
string keyName = Path.GetDirectoryName(fullPath);
string valueName = Path.GetFileName(fullPath);
return Registry.GetValue(keyName, valueName, defaultValue);
或者你可以使用Registry.LocalMachine
通过这个http://www.csharphelp.com/2007/01/registry-ins-and-outs-using-c/
【讨论】:
以上是关于从注册表中读取值的主要内容,如果未能解决你的问题,请参考以下文章
如何在 C++ 中使用 RegQueryValueEx(..) 从注册表中读取 REG_MULTI_SZ 类型值