Click here to Skip to main content
Click here to Skip to main content

A C# class that deals with System Registry

By , 31 Mar 2002
 

Introduction

Let me introduce to you a class (made in C#, of course) that will help you to perform all necessary System Registry operations, such as retrieving and setting Registry keys and values.

So, what class can my do? My clsRegistry has 10 useful methods that provide you with an easy-to-understand interface to the C# built-in Registry functions. All Registry functions in C# are implemented inside the Microsoft.Win32 namespace, so when you are going to work with the System Registry, do not forget to include the "using Microsoft.Win32;" declaration to your project ... or simply use the clsRegistry class.

clsRegistry's Description

The class methods are:

  • GetStringValue

    Retrieves the specified String value. Returns a System.String object.

  • GetDWORDValue

    Retrieves the specified DWORD value. Returns a System.Int32 object. *

  • GetBinaryValue

    Retrieves the specified Binary value. Returns a System.Byte[] object.

  • SetStringValue

    Sets/creates the specified String value.

  • SetDWORDValue

    Sets/creates the specified DWORD value. *

  • SetBinaryValue

    Sets/creates the specified Binary value.

  • CreateSubKey

    Creates a new subkey or opens an existing subkey.

  • DeleteSubKeyTree

    Deletes a subkey and any child subkeys recursively.

  • DeleteValue

    Deletes the specified value from this (current) key.

  • GetValueType

    Retrieves the type of the specified Registry value.

* Normally, when you are creating a DWORD Registry value, it should be an Unsigned 32-bit integer value (or System.UInt32 or simply uint) with the range from 0 to 4,294,967,295. BUT!!! The Microsotf.Win32.RegistryKey.SetValue() method forces it to be a Signed 32-bit integer (or System.Int32 or simply int) with the range from -2,147,483,648 to 2,147,483,647. If you try to assign a value that is bigger than 2,147,483,647 then the String value is created. So, brothers, PLEASE, BE EXTREMELY CAREFUL here to avoid the unwished consequences!!!

I do not know yet if this is a bug or some kind of a new convention.

How to Include the clsRegistry Class to your Project

Create a New Application using the Console Application template and call it "RegClassTest". Actually, the type of Application doesn't matter in our case; Console Application is just my preference. It might be a Windows Application or whatever - you choose. Now (just for your own comfort) you may copy the clsRegistry.cs file to your project's folder. Then go to the "Project" menu and click on the "Add Existing Item..." or simply press ALT+SHIFT+A to open the Add Item Dialog. Find the clsRegistry.cs file, select it and click "Open". Check out the Solution Explorer window: our file should be added to the project.

clsRegistry: Class Usage

Once you added clsRegistry.cs to your project, double-click it to edit the code. Now replace the following line...

namespace RegistryClass

... with this one:

namespace RegClassTest

Here, instead of "RegClassTest" you will type the namespace' name of your project.

Now save your project and pass to your project's main class and open the code window. In order to start using our clsRegistry class, we must create a new instance of the class. It is done this way:

//don't forget about Microsoft.Win32 namespace
//if you are going to use the C# Registry functions
using Microsoft.Win32;

static void Main(string[] args)
{
    clsRegistry reg = new clsRegistry(); //create new instance of clsRegistry class
    ...
}

IMPORTANT: The functions don't return error codes. For this purpose, the strRegError variable is provided. This variable always contains the error message of the last operation performed, or null if no error occurred. I would advise you to check for errors every time you use clsRegistry's functions. How to invoke a class function and how to check for errors is showed in the example below:

static void Main(string[] args)
{
    clsRegistry reg = new clsRegistry(); //create new instance of clsRegistry class

    /*========= WORKING WITH STRING VALUES =========*/
    Console.WriteLine ("/*========= WORKING WITH STRING VALUES =========*/");
    // Set string value
    Console.WriteLine ("SET");
    reg.SetStringValue (
        Registry.LocalMachine,
        "SOFTWARE\\RegClassTest",
        "myStringValue",
        "Mama, I've just set a string value :-)"
        );
    if (reg.strRegError == null)
        Console.WriteLine ("\"myStringValue\" has been successfully set");
    else
        Console.WriteLine ( "Error: " + reg.strRegError );

    // Get string value
    Console.WriteLine ("GET");
    string strValue = reg.GetStringValue (
        Registry.LocalMachine,
        "SOFTWARE\\RegClassTest",
        "myStringValue"
        );
    if (reg.strRegError == null)
        Console.WriteLine ("myStringValue = \"{0}\"", strValue);
    else
        Console.WriteLine ( "Error: " + reg.strRegError );

    Console.WriteLine ("\npress return to exit");
    Console.ReadLine ();
}

If you insert the code above and Run the project, you'll have the following output:

I've prepared a full sample for you - a sample project that shows how to retrieve and set String, DWORD and Binary values, how to get the value's type, how to create new values and how to delete Registry values and keys.

After executing the full sample, you should get the following output:

Afterword

I have been looking for a class that deals with Registry for a long time. But I found nothing (even on MSDN). So I wrote the clsRegistry. This is something like the first try. I hope you'll help me to expand and improve it. Your suggestions are welcome as always.

- Alexandr Khilov

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Alexandr_K
Web Developer
Canada Canada
Member
Years of programming...

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralCode tipsmemberAndy Smith30 Mar '02 - 14:26 
While the _idea_ of the code is probably usefull, I think there are several ways to make the implementation better.
 
1) Get rid of all that hungarian notation ugliness from the public names. I don't care at all what you use internally... but the public names, such as the class name, the method names, etc, should be stripped of their warts. also, there is absolutely zero reason to have those "myReg_" prefixes on every method.
 
2) Replace all those "set the error message and return null" areas with Exceptions. If you aren't sure what Exception to use, use the InvalidOperationException.
 
3) What is the point of having those Long and Ugly RegistryKey mappings to the simple Register.XXXX RegistryKeys? They should be removed and people should be using the normal values.
 
4) Comments Comments Comments. It's nice that it works. It would be better if there were comments. Also, look into adding some xml comments. It's a very nice feature of C#.
GeneralRe: Code tipsmemberAlexandr Khilov1 Apr '02 - 3:09 
Andy, thanks for tips.
Look for the updated code and article soon.
 
Anyway, I believe my work could be used as a base by those who need a class like this.
Good Luck.

GeneralRe: Code tipsmemberAndy Smith1 Apr '02 - 5:24 
I was just looking at the code again...
had a couple more ideas.
 
1) you should make the methods "static" and make the constructor "private". Since there are no class-level variables, I don't see why one should have to create an instance of the class.
 
2) provide default values in the Get operations, and return the default instead of generating an error.
GeneralRe: Code tipsmemberAlexandr Khilov1 Apr '02 - 11:36 
Perhaps, you are right about the class instance.
Anyway, if someone's going to use this code, he's free to modify it the way he wants.
 
Ah, thanks again for your tips. I've already applied some of them.
GeneralRe: Code tipsmemberriscy21 Apr '05 - 20:34 
Andy,
 
Would by any chance give us a sample program on how it should operates,
 
Thanks
 
Regards
 
Electronic Engineer keen to learn more of C# and .net programming. Currently using C and C++ for microcontroller application.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 1 Apr 2002
Article Copyright 2002 by Alexandr_K
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid