Wednesday, May 21, 2008

How to Write & Read from Windows Registry using C#?

So we need to store our settings!

Since writing to INI files is kind of out dated, writing settings to the windows registry seems to be good enough. (its not new, even windows 3.1 had it... and the whole reg thing seems to be getting out dated too... lets forget about that and assume its good for the moment.)


So How to write & read from Windows Registry using C#?

I can straight away give you the code... but that doesn't seem to be not quite satisfying.

For those who are not familiar with Windows Registry, i'd give a simple briefing here.


Windows registry is the hive of logical information where windows OS it self and other applications keep their settings/configuration/etc data stored.


CAUTION: Making un-necessary changes to the existing registry items may cause malfunctioning of Windows OS or other applications. So beware!


Windows registry is designed in a hierarchical structure, with keys, sub keys and different types of values stored inside keys.

Following screenshot is an illustrated view of windows registry, that will give u a basic idea.




[click on image to see in full size]
What you see there is the windows built in registry editor (regedit.exe) u can use it to manually edit/view registry.

Windows registry is separated into several sections catering several purposes.

Sections/hives are as follows:

HKEY_CLASSES_ROOT (HKCR) - stores information about reged applications; file associations, OLE Object Class IDs.
HKEY_CURRENT_USER (HKCU) - stores settings specific to the currently logged-in user.
HKEY_LOCAL_MACHINE (HKLM)- stores settings that are general to all users on the computer. Contains four subkeys, SAM, SECURITY, SOFTWARE and SYSTEM. Subkey, HARDWARE, is volatile and is created dynamically.
HKEY_USERS (HKU) - contains subkeys corresponding to the HKEY_CURRENT_USER keys for each user profile actively loaded on the machine
HKEY_CURRENT_CONFIG - contains information gathered at runtime, compiled at boot; information stored in this key is not permanently stored.
HKEY_PERFORMANCE_DATA - provides runtime information into performance data provided by either the NT kernel itself or other programs that provide performance data. This key is not displayed in the Registry Editor, but it is visible through the registry functions in the Windows API.

So now you can decide where u gonna store your reg values.

Then lets get into business! Here goes the code:
(These code snippets uses, "Microsoft.Win32" namespace.)

Writing a Key to Registry
=========================
///
/// Method to write a key & values to windows registry
///

private void writeReg()
{
// definition of registry key - keylevel node
// notice that here we are creating key in "CurrentUser"... u can alter this to suite your needs.
RegistryKey myKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\\TestKey\\TestSubKey");
// check whether the key already exists
if (myKey == null)
{
MessageBox.Show("Null Masterkey!");
}
// if not
else
{
try
{
// set sample values
myKey.SetValue("MyKey", "MyValue1");
myKey.SetValue("xKey", "xValue-bhooo");
MessageBox.Show("Keys set!");
}
catch (Exception ex)
{
// ops!!
MessageBox.Show(ex.Message);
}
finally
{
// close RegistryKey
myKey.Close();
}
}
}


Reading a value from Registry
=============================
///
/// Method to read a value from windows registry
///

private void readRed()
{
string myregstring = "";
// open key
// notice that here our key is in "CurrentUser"... u can alter this to suite your needs.
RegistryKey myKey1 = Registry.CurrentUser.OpenSubKey("SOFTWARE\\TestKey\\TestSubKey");
// if key does not exsists
if (myKey1 == null)
{
MessageBox.Show("Non exsisting key!");
}
// if key exsists
else
{
try
{ // get reg value into a string
myregstring = (string)myKey1.GetValue("xKey");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
// close RegistryKey
myKey1.Close();
}
MessageBox.Show(myregstring);
}
}


Delete a key from Registry
==========================
///
/// Method to delete a key in windows registry
///

private void delKey()
{
// notice the overloaded OpenSubKey method now uses two arguments.
// second argument: bool writable - if true key will open in writeble mode.
RegistryKey myKey2 = Registry.CurrentUser.OpenSubKey("SOFTWARE\\TestKey",true);
// if key does not exsists
if (myKey2 == null)
{
MessageBox.Show("Non exsisting key!");
}
// if key exsists
else
{
try
{
// delete the given key
myKey2.DeleteSubKey("TestSubKey");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
// close RegistryKey
myKey2.Close();
}
}
}


Delete a key-tree from Registry
===============================
///
/// Method to delete a key and its tree (including sub-elements) in windows registry
///

private void delKeyTree()
{
// notice the overloaded OpenSubKey method now uses two arguments.
// second argument: bool writable - if true key will open in writeble mode.
RegistryKey myKey3 = Registry.CurrentUser.OpenSubKey("SOFTWARE\\TestKey",true);
// if key does not exsists
if (myKey3 == null)
{
MessageBox.Show("Non exsisting key!");
}
// if key exsists
else
{
try
{
// delete the given key
myKey3.DeleteSubKeyTree("TestSubKey");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
// close RegistryKey
myKey3.Close();
}
}
}


There are additional registry fuctions such as; count keys and count values which are not common in use and therefore not discusses here. See MSDN ;)

You can download a sample visual studio solution (C# project) that illustrate these codes from my website. [www.thekalana.net/downloads.html]

If you like to know more about windows registry, i'd recommend you to read: http://en.wikipedia.org/wiki/Windows_Registry

No comments: