Custom Search

Saturday, June 7, 2008

Accessing the Registry for reading keys in C#

C# contains class object that make the job of manipulating the registry very easy.
Also, the registry is indexed that make much faster the reading job.

Ok, let’s now proceed to read from the registry.
First you need to make the import of the Microsoft.Win32 namespace that contains the registry access functions.
The second important thing you need to use RegistryKey object to make the actual reading.

Let’s now write a small piece of code to see how this works.

using System;
using System.Text;
using Microsoft.Win32;

namespace RegRead

class Program

static void Main(string[] args)

//Example 1
RegistryKey RegKey = Registry.LocalMachine;
RegKey = RegKey.OpenSubKey(
Object cpuName = RegKey.GetValue("ProcessorNameString");
Console.WriteLine("Your CPU name is:" + cpuName);


//Example 2
RegistryKey RegKey2 = Registry.CurrentUser;
RegKey2 = RegKey2.OpenSubKey("Printers");
Object printerName = RegKey2.GetValue("DeviceOld");
Console.WriteLine("Your Printer name is: " + printerName);


The first thing you need to do is to import the Microsoft.Win32 namespace.
Then, if you look at the definition of the instance of the RegistryKey object, you will see that it is pointing to Local Machine, which means that the HKEY_LOCAL_MACHINE folder will be enable for reading.

(To open the Registry editor just go to start->Run: regedit).
After this step, we simple need to find the folders/subfolders where the key is located and read it.

The second example is pretty much the same. The only major difference is that the
HKEY_CURRENT_USER folder will be available.

No comments: