Reading/Writing Registry in .NET
Submitted by Date of Submission User Level
Mahesh Chand 02/20/2001 Beginner
If you have ever read/write registry using Win APIs RegOpenKeyEx, RegCreateKeyEx, and RegCloseKey, you must be familiar with the complexity of these APIs. In .NET framework, the Registry and the RegistryKey classes provide control to the Windows Registry. These classes are easy to use.
These classes are defined in Microsoft.Win32 namespace and mscorlib.dll assembly. You need to use the namespace and the assembly before use these classes.
#using
using namespace Microsoft::Win32;
The Registry class only have seven field members which gives you access to particular area of the registry. It's similar to opening a key in the registry. These all members return a pointer to RegistryKey.
ClassesRoot The Windows Registry base key HKEY_CLASSES_ROOT.
CurrentConfig The Windows Registry base key HKEY_CURRENT_CONFIG.
CurrentUser The Windows Registry base key HKEY_CURRENT_USER.
DynData The Windows Registry base key HKEY_DYN_DATA.
LocalMachine The Windows Registry base key HKEY_LOCAL_MACHINE.
PerformanceData The Windows Registry base key HKEY_PERFORMANCE_DATA.
Users The Windows Registry base key HKEY_USERS.
Say you want to read/write data of HKEY_LOCAL_MACHINE.
RegistryKey* pRegKey = Registry::LocalMachine;
Now you call OpenSubKey of RegistryKey to open a key and GetValue to get the value of a string.
pRegKey->OpenSubKey(L"SOFTWARE\\Kruse Inc\\Version");
Object *pValue = pRegKey->GetValue(L"kWise");
The SetValue member of this class is used to write a value for a registry key.
pRegKey->SetValue(L"kWise", "some Value Here");
You use DeleteValue to delete a value.
pRegKey->DeleteValue(L"kWise");
Other members:
DeleteSubKey Deletes a subkey
CreateSubKey Opens a subkey if key is already exists. Creates new otherwise.
DeleteSubKeyTree Deletes subkey and its nodes
Sample Example:
#using
using namespace System;
using namespace Microsoft::Win32;
// This is the entry point for this application
int main(void)
{
RegistryKey * pRegKey = Registry::LocalMachine;
pRegKey = pRegKey->OpenSubKey(L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0");
Object *pValue = pRegKey->GetValue(L"VendorIdentifier");
Console::WriteLine(L"The central processor of this machine is: {0}.", pValue);
return 0;
}