获取注册表中的项
本文关键字:注册表 获取 | 更新日期: 2023-09-27 18:20:30
如何获取等注册表文件夹中的所有注册表子项
SOFTWARE'Microsoft'Windows'CurrentVersion'Run'
使用foreach语句,我将如何实现这一点?
使用Microsoft.Win32.Registry对象:
private Dictionary<string, object> GetRegistrySubKeys()
{
var valuesBynames = new Dictionary<string, object>();
const string REGISTRY_ROOT = @"SOFTWARE'Microsoft'Windows'CurrentVersion'Run'";
//Here I'm looking under LocalMachine. You can replace it with Registry.CurrentUser for current user...
using (RegistryKey rootKey = Registry.CurrentUser.OpenSubKey(REGISTRY_ROOT))
{
if (rootKey != null)
{
string[] valueNames = rootKey.GetValueNames();
foreach (string currSubKey in valueNames)
{
object value = rootKey.GetValue(currSubKey);
valuesBynames.Add(currSubKey, value);
}
rootKey.Close();
}
}
return valuesBynames;
}
确保添加适当的"使用"声明:
using Microsoft.Win32;
如果它是密钥的值字符串
string[] names = Registry.CurrentUser.OpenSubKey(@"SOFTWARE'Microsoft'Windows'CurrentVersion'Run'").GetSubKeyNames();
//dont call both at same time....
string[] values = Registry.CurrentUser.OpenSubKey(@"SOFTWARE'Microsoft'Windows'CurrentVersion'Run'").GetValueNames();
foreach (string key in values)
{
//do your stuff...
}
您需要导入命名空间
using Microsoft.Win32;
//also...
//retrieves the count of subkeys in the key.
int count = Registry.CurrentUser.OpenSubKey(@"SOFTWARE'Microsoft'Windows'CurrentVersion").SubKeyCount;
也可以看看这篇文章,可能会对你的任务有所帮助http://www.codeproject.com/Articles/3389/Read-write-and-delete-from-registry-with-C
编辑:
取自代码项目文章以阅读关键
public string Read(string KeyName)
{
// Opening the registry key
RegistryKey rk = baseRegistryKey ;
// Open a subKey as read-only
RegistryKey sk1 = rk.OpenSubKey(subKey);
// If the RegistrySubKey doesn't exist -> (null)
if ( sk1 == null )
{
return null;
}
else
{
try
{
// If the RegistryKey exists I get its value
// or null is returned.
return (string)sk1.GetValue(KeyName.ToUpper());
}
catch (Exception e)
{
// AAAAAAAAAAARGH, an error!
ShowErrorMessage(e, "Reading registry " + KeyName.ToUpper());
return null;
}
}
}