How to: Read Data from the Windows Registry (C++/CLI)


The following code example uses the CurrentUser key to read data from the Windows registry. First, the subkeys are enumerated using the GetSubKeyNames method and then the Identities subkey is opened using the OpenSubKey method. Like the root keys, each subkey is represented by the RegistryKey class. Finally, the new RegistryKey object is used to enumerate the key/value pairs.


// registry_read.cpp  
// compile with: /clr  
using namespace System;  
using namespace Microsoft::Win32;  
int main( )  
   array<String^>^ key = Registry::CurrentUser->GetSubKeyNames( );  
   Console::WriteLine("Subkeys within CurrentUser root key:");  
   for (int i=0; i<key->Length; i++)  
      Console::WriteLine("   {0}", key[i]);  
   Console::WriteLine("Opening subkey 'Identities'...");  
   RegistryKey^ rk = nullptr;  
   rk = Registry::CurrentUser->OpenSubKey("Identities");  
   if (rk==nullptr)  
      Console::WriteLine("Registry key not found - aborting");  
      return -1;  
   Console::WriteLine("Key/value pairs within 'Identities' key:");  
   array<String^>^ name = rk->GetValueNames( );  
   for (int i=0; i<name->Length; i++)  
      String^ value = rk->GetValue(name[i])->ToString();  
      Console::WriteLine("   {0} = {1}", name[i], value);  
   return 0;  

The Registry class is merely a container for static instances of RegistryKey. Each instance represents a root registry node. The instances are ClassesRoot, CurrentConfig, CurrentUser, LocalMachine, and Users.

In addition to being static, the objects within the Registry class are read-only. Furthermore, instances of the RegistryKey class that are created to access the contents of the registry objects are read-only as well. For an example of how to override this behavior, see How to: Write Data to the Windows Registry (C++/CLI).

There are two additional objects in the Registry class: DynData and PerformanceData. Both are instances of the RegistryKey class. The DynData object contains dynamic registry information, which is only supported in Windows 98 and Windows Me. The PerformanceData object can be used to access performance counter information for applications that use the Windows Performance Monitoring System. The PerformanceData node represents information that is not actually stored in the registry and therefore cannot be viewed using Regedit.exe.

How to: Write Data to the Windows Registry (C++/CLI)
Windows Operations (C++/CLI)
.NET Programming with C++/CLI (Visual C++)