Daniel Jones
Daniel Jones

Reputation: 109

Get keys in registry

How do I get all registry sub keys in a registry folder such as

SOFTWARE\Microsoft\Windows\CurrentVersion\Run\

using a foreach statement how would i accomplish this?

Upvotes: 0

Views: 8021

Answers (2)

Avi Turner
Avi Turner

Reputation: 10456

Use the Microsoft.Win32.Registry object:

 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;
 }

Make sure to add the appropriate "using" declaration:

using Microsoft.Win32;

Upvotes: 4

terrybozzio
terrybozzio

Reputation: 4542

if its the string of values of the keys

    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...            
}

you need to import namespace

using Microsoft.Win32;
//also...
//retrieves the count of subkeys in the key.
int count = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion").SubKeyCount;

also check this article,might help you in your task http://www.codeproject.com/Articles/3389/Read-write-and-delete-from-registry-with-C

EDIT:

taken from codeproject article to read a key

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;
        }
    }
}

Upvotes: 0

Related Questions