Search code examples
c#cwindowswinapiregistry

How do I access the registry, and loop through keys in C (Example C# code provided)?


I basically want to perform the same functions as this code, but in C.

RegistryKey regAdapters = Registry.LocalMachine.OpenSubKey ( AdapterKey, true);
    string[] keyNames = regAdapters.GetSubKeyNames();
    char[] devGuid;
    foreach(string x in keyNames)
    {
        RegistryKey regAdapter = regAdapters.OpenSubKey(x);
        object id = regAdapter.GetValue("ComponentId");
        if (id != null && id.ToString() == "tap0801") devGuid = regAdapter.GetValue("NetCfgInstanceId").ToString();
    }

Solution

  • There's actually no recursion there. The code just opens a key under HKLM, enumerates all sub-keys, and looks for a particular named value. In outline, your C code would be made up from these Win32 API calls:

    HKEY hRegAdapters;
    LONG res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AdapterKey, 0,
      KEY_READ, &hRegAdapters);
    // error checking by testing res omitted
    

    Now that you have opened the key you can enumerate sub keys:

    for (DWORD Index=0; ; Index++)
    {
        char SubKeyName[255];
        DWORD cName = 255;
        LONG res = RegEnumKeyEx(hRegAdapters, Index, SubKeyName, &cName, 
            NULL, NULL, NULL, NULL);
        if (res != ERROR_SUCCESS)
            break;
        // do something with Name
    }
    

    Now that you have the name of each sub-key, you can read the values with RegGetValue:

    char Value[64];
    DWORD cbData = 64;
    LONG res = RegGetValue(hSubKey, SubKeyName, "ComponentId",
        RRF_RT_REG_SZ, NULL, Value, &cbData);
    // check for errors now before using Value
    

    RegGetValue is a convenience function added in Vista. If you need your code to run on XP then you'll have to call RegQueryValueEx instead. That involves opening the "ComponentId" subkey first.

    Note that I've omitted all error checking and also ignored the issue of Unicode and called the ANSI APIs. I'll leave all those details to you.

    Remember to call RegCloseKey(hRegAdapters) when you have finished.

    Refer to the MSDN documentation for all the gory details of how to access the registry.