0

如何获取注册表文件夹中的所有注册表子项,例如

SOFTWARE\Microsoft\Windows\CurrentVersion\Run\

使用 foreach 语句我将如何做到这一点?

4

2 回答 2

3

使用 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;
于 2013-06-30T03:26:32.097 回答
0

如果它是键值的字符串

    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

编辑:

取自codeproject文章以阅读关键

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;
        }
    }
}
于 2013-06-30T03:23:23.227 回答