Registry Handling Using C#: Basic

Introduction

Since we have used the Registry Editor so often for so many reasons and quite often we have used it for tweaks or some hacks. Here, we will manipulate the Registry Editor's sub-keys in their directory using C# code.

Registry Editor

Background

There is a builtin class for this, so there is no need to include any references. We will use the class from the namespace "Microsoft.Win32".

Procedure

Step 1: Try to create a look alike Form using a Group Box and some Buttons, Labels and TextBoxes.

Creating Form

In the first Group Box, we will create a key to the specified Location (in other words trying to add a key),

In the second Group Box, we try to get the value of the specified key (in other words try to fetch the value of a key).

In the third Group Box, we will delete the key.

So, let's move further.

Step 2: Create a reference of a RegistryKey to assign the value of a SubKey.

Add this in the class section:

RegistryKey

Here we are trying to create a MyTest Directory in "HKEY_CURRENT_USER\Software" (Default Location).

Actually, we have created a directory in "HKEY_CURRENT_USER\Software\MyTest".

Step 3: Create the "Add" button.

Add Button Code

Here, we saved the value of the key and value in two defined strings and ed them to the SetValue() method of Registry Key.

At last, clear the Text Boxes using the Clear() method.

From this we have set up the Sub-Key in the specifed directory.

Specified Directory

Step 4: Create the retrival.

Retrieval Code

First we will enable the TextBox, since I have diasbled (Enable=false) in the default condtion.

It will then check for the TextBox that, is it NULL or not.

If not, then try to get the value using the GetValue() method and you need to cast it to a String type since it is an Object type.

Step 5: Create the "Delete" button.

Delete Button Code

Since we need to be in a different Stream, SO, either use the same refrence or create a new one for the open Stream.

And, use the DeleteSubKeyTree() or DeleteSubKey() method for the job.

At last, close the stream using the Close() method.

Ultimately, you get your output in this way:

DeleteSubKey Method

And, in the Registry Window you will have this:

Registry Window

Conclusion

We have created a Sub-Key in the Registry and then saved some value to it using "SetValue". Then retrieve its value using "GetValue".

And finally, delete the Sub-Key that was created using the "SubKeyTree()" method.


Recommended Free Ebook
Similar Articles