有没有一种方法可以只调用注册表一次并提取各种键值

时间:2019-04-04 13:27:28

标签: c# registry

我基本上是在注册表路径下阅读

SOFTWARE\\WOW6432Node\\Microsoft

但是我有不同的sub keyskeys来阅读。

示例

  1. VersionSOFTWARE\\WOW6432Node\\Microsoft\\DataAccess
  2. NodePath9SOFTWARE\\WOW6432Node\\Microsoft\\ENROLLMENTS\\ValidNodePaths

目前,我可以一一阅读它,但是什么方式才能使我只需要去一次注册表,并且可以用C#代码进行所有其他操作?

我可以一次读取所有信息(以便一次调用注册表),直到SOFTWARE\\WOW6432Node\\Microsoft并使用C#代码进行其余工作吗?

var X1 = GetRegistryValue("SOFTWARE\\WOW6432Node\\Microsoft\\DataAccess", "Version");
            var X2 = GetRegistryValue("SOFTWARE\\WOW6432Node\\Microsoft\\ENROLLMENTS\\ValidNodePaths", "NodePath9");



 private static string GetRegistryValue(string subKey, string keyName)
    {
        using (RegistryKey key = Registry.LocalMachine.OpenSubKey(subKey))
        {
            if (key != null)
            {
                if (key.GetValue(keyName) != null)
                {
                    return (string)key.GetValue(keyName);
                }
            }

            return null;
        }
    }

1 个答案:

答案 0 :(得分:1)

OpenSubKey()方法返回一个注册表项,因此您可以先创建一个公用密钥,然后将其传递到GetRegistryValue() ...

private static RegistryKey GetCommonKey(string subKey)
{
    return Registry.LocalMachine.OpenSubKey(subKey);
}

private static string GetRegistryValue(RegistryKey commonKey, string subKey, string keyName)
{
    using (commonKey.OpenSubKey(subKey))
    {
        if (key != null)
        {
            if (key.GetValue(keyName) != null)
            {
                return (string)key.GetValue(keyName);
            }
        }
        return null;
    }
}

// usage

var commonKey = GetCommonKey("SOFTWARE\\WOW6432Node\\Microsoft");
var version = GetRegistryValue(commonKey, "DataAccess", "Version");
var nodePath = GetRegistryValue(commonKey, "ENROLLMENTS\\ValidNodePaths", "Version");
相关问题