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

问题描述 投票:1回答:1

我基本上阅读下面的注册表路径,

SOFTWARE\\WOW6432Node\\Microsoft

但我有不同的sub keyskeys阅读。

  1. Version下的SOFTWARE\\WOW6432Node\\Microsoft\\DataAccess
  2. NodePath9下的SOFTWARE\\WOW6432Node\\Microsoft\\ENROLLMENTS\\ValidNodePaths
  3. 等等

目前我能够一个一个地阅读它,但是有什么方法让我只需要一次登记注册表,我可以用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;
        }
    }
c# registry
1个回答
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");
© www.soinside.com 2019 - 2024. All rights reserved.