Wednesday, August 25, 2010

Registry Tutorial

Today I want to show you how to manage the registry in C#. In this Windows saves information about programms etc., normally it can be accessed via the registry editor (Start - Execute - regedit).
In C# the management is done by the class RegistryKey, which is contained in Microsoft.Win32. For all following code samples I therefor assume

using Microsoft.Win32;
The registry is divided in different categories, on the first level of hierarchy there are for example the groups HKEY_CURRENT_USER (saves settings of the current user) or HKEY_LOCAL_MACHINE (saves settings of the whole computer).
To be able to "use" the registry, first an instance of the class RegistryKey has to be initialized with one of these, for example with:

RegistryKey SampleKey = Registry.CurrentUser;

One can maneuver deeper into the tree with the function OpenSubKey():

RegistryKey DeeperKey = SampleKey.OpenSubKey("Software\\7-Zip"true);

The 2nd parameter of the type Boolean describes, whether the is to be opened with writing rights or not.
DeeperKey then saves the selected key.
For the elementary use there are now only 5 more methods, which I will show directly in an example:
DeeperKey.CreateSubKey("Testkey");
Creates a subkey, if this already exists it is opened
Object TestValue = DeeperKey.GetValue("Lang");
Reads the value "Lang" of the key DeeperKey.
DeeperKey.SetValue("NewValue""randomdata");
Writes "randomdata" in the value "NewValue". If it does not exist yet, it gets created
DeeperKey.DeleteValue("NewValue");
Deletes the value "NewValue".
DeeperKey.DeleteSubKey("Testkey");
Deletes the subkey "Testkey".

Finally, the used objects should be disposed when not used anymore, as the same holds for files etc.
This can be done by the function Close() of the class RegistryKey.

No comments:

Post a Comment