Click here to Skip to main content
11,636,300 members (74,898 online)
Click here to Skip to main content

Read, write and delete from registry with C#

, 17 Dec 2002 591.5K 24.1K 164
Rate this:
Please Sign up or sign in to vote.
An useful simple class to read, write, delete values from registry with C#.

Introduction

I've done a little update, now this class provides six functions:

  • Read to read a registry key.
  • Write to write into a registry key.
  • DeleteKey to delete a registry key.
  • DeleteSubKeyTree to delete a sub key and any child.
  • SubKeyCount to retrieve the count of subkeys at the current key.
  • ValueCount to retrieve the count of values in the key.

and three properties:

  • ShowError to show or hide error messages (default = false).
  • SubKey to set the subkey value (default = "SOFTWARE\\" + Application.ProductName).
  • BaseRegistryKey to set the base registry key value (default = Registry.LocalMachine).

Source code

Importing other namespaces...

using System;
// it's required for reading/writing into the registry:
using Microsoft.Win32;      
// and for the MessageBox function:
using System.Windows.Forms;

Read function

  • input: the key name (string)
  • output: value of the key (string)
public string Read(string KeyName)
{
    // Opening the registry key
    RegistryKey rk = baseRegistryKey ;
    // Open a subKey as read-only
    RegistryKey sk1 = rk.OpenSubKey(subKey);
    // If the RegistrySubKey doesn't exist -> (null)
    if ( sk1 == null )
    {
        return null;
    }
    else
    {
        try 
        {
            // If the RegistryKey exists I get its value
            // or null is returned.
            return (string)sk1.GetValue(KeyName.ToUpper());
        }
        catch (Exception e)
        {
            // AAAAAAAAAAARGH, an error!
            ShowErrorMessage(e, "Reading registry " + KeyName.ToUpper());
            return null;
        }
    }
}

Write function

  • input: the key name (string) and its value (object)
  • output: true if OK or false if error
public bool Write(string KeyName, object Value)
{
    try
    {
        // Setting
        RegistryKey rk = baseRegistryKey ;
        // I have to use CreateSubKey 
        // (create or open it if already exits), 
        // 'cause OpenSubKey open a subKey as read-only
        RegistryKey sk1 = rk.CreateSubKey(subKey);
        // Save the value
        sk1.SetValue(KeyName.ToUpper(), Value);

        return true;
    }
    catch (Exception e)
    {
        // AAAAAAAAAAARGH, an error!
        ShowErrorMessage(e, "Writing registry " + KeyName.ToUpper());
        return false;
    }
}

DeleteKey function

  • input: the key name (string)
  • output: true if OK or false if error
public bool DeleteKey(string KeyName)
{
    try
    {
        // Setting
        RegistryKey rk = baseRegistryKey ;
        RegistryKey sk1 = rk.CreateSubKey(subKey);
        // If the RegistrySubKey doesn't exists -> (true)
        if ( sk1 == null )
            return true;
        else
            sk1.DeleteValue(KeyName);

        return true;
    }
    catch (Exception e)
    {
        // AAAAAAAAAAARGH, an error!
        ShowErrorMessage(e, "Deleting SubKey " + subKey);
        return false;
    }
}

DeleteSubKeyTree function

  • input: void
  • output: true if OK or false if error
public bool DeleteSubKeyTree()
{
    try
    {
        // Setting
        RegistryKey rk = baseRegistryKey ;
        RegistryKey sk1 = rk.OpenSubKey(subKey);
        // If the RegistryKey exists, I delete it
        if ( sk1 != null )
            rk.DeleteSubKeyTree(subKey);

        return true;
    }
    catch (Exception e)
    {
        // AAAAAAAAAAARGH, an error!
        ShowErrorMessage(e, "Deleting SubKey " + subKey);
        return false;
    }
}

SubKeyCount function

  • input: void
  • output: number of subkeys at the current key
public int SubKeyCount()
{
    try
    {
        // Setting
        RegistryKey rk = baseRegistryKey ;
        RegistryKey sk1 = rk.OpenSubKey(subKey);
        // If the RegistryKey exists...
        if ( sk1 != null )
            return sk1.SubKeyCount;
        else
            return 0; 
    }
    catch (Exception e)
    {
        // AAAAAAAAAAARGH, an error!
        ShowErrorMessage(e, "Retriving subkeys of " + subKey);
        return 0;
    }
}

ValueCount function

  • input: void
  • output: number of values in the key
public int ValueCount()
{
    try
    {
        // Setting
        RegistryKey rk = baseRegistryKey ;
        RegistryKey sk1 = rk.OpenSubKey(subKey);
        // If the RegistryKey exists...
        if ( sk1 != null )
            return sk1.ValueCount;
        else
            return 0; 
    }
    catch (Exception e)
    {
        // AAAAAAAAAAARGH, an error!
        ShowErrorMessage(e, "Retriving keys of " + subKey);
        return 0;
    }
}

ShowErrorMessage function

This is a private function to show the error message if the property showError = true.

private void ShowErrorMessage(Exception e, string Title)
{
    if (showError == true)
        MessageBox.Show(e.Message,
                Title
                ,MessageBoxButtons.OK
                ,MessageBoxIcon.Error);
}

Using the code

First of all, you have to import its namespace:

using Utility.ModifyRegistry;

and to instantiate your class:

ModifyRegistry myRegistry = new ModifyRegistry();

The three properties have already their default values. However, you can modify them:

property default value example
ShowError false myRegistry.ShowError = true;
BaseRegistryKey Registry.LocalMachine myRegistry.BaseRegistryKey = Registry.CurrentUser;
SubKey "SOFTWARE\\" + Application.ProductName myRegistry.SubKey = "SOFTWARE\\MYPROGRAM\\MYSUBKEY";

OK, now you can read, write, and delete from your registry.

To read:

myRegistry.Read("MY_KEY");

Note: if MY_KEY doesn't exist, the Read function will return null.

To write:

myRegistry.Write("MY_KEY", "MY_VALUE");

Note: if the SubKey doesn't exist, it will be automatically created.

To delete a single key:

myRegistry.DeleteKey("MY_KEY");

Note: also if the MY_KEY doesn't exist, this function will return TRUE.

To delete the subkey tree:

myRegistry.DeleteSubKeyTree();

Note: this code will delete the SubKey and all its children.

To retrieve the count of subkeys at the current key:

myRegistry.SubKeyCount();

To retrieve the count of values in the key:

myRegistry.ValueCount();

Example

The following code is an example from my in progress RTF file editor program. This code retrieves the "Recent files" list from registry:

[...]
ModifyRegistry myRegistry = new ModifyRegistry();
myRegistry.SubKey = "SOFTWARE\\RTF_SHARP_EDIT\\RECENTFILES";
myRegistry.ShowError = true;
int numberValues = myRegistry.ValueCount();

for (int i = 0; i < numberValues; i++)
{
    arrayRecentFiles[i] = myRegistry.Read(i.ToString());
    [...]

and this code writes the "Recent files" list into registry:

ModifyRegistry myRegistry = new ModifyRegistry();
myRegistry.SubKey = "SOFTWARE\\RTF_SHARP_EDIT\\RECENTFILES";
myRegistry.ShowError = true;
myRegistry.DeleteSubKeyTree();
for (int i = 0; i < 8 ; i++)
{
    if (arrayRecentFiles[i] == null)
        break;
    myRegistry.Write(i.ToString(), arrayRecentFiles[i]);
}

Conclusion

The .NET framework has a lot of functions to read and modify the registry, my class is only a start point. I hope this helps!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Francesco Natali
Web Developer
Italy Italy
No Biography provided

You may also be interested in...

Comments and Discussions

 
Questiongreat article Pin
cw229013-Jul-15 6:07
membercw229013-Jul-15 6:07 
GeneralGreat stuff Pin
Windy Hendwiananda20-Jun-15 5:51
professionalWindy Hendwiananda20-Jun-15 5:51 
Suggestiondefault value if not found Pin
richard525417-Feb-15 22:51
memberrichard525417-Feb-15 22:51 
QuestionBase of Registry.LocalMachine does not work Pin
Andrew Morpeth4-Jan-15 14:17
memberAndrew Morpeth4-Jan-15 14:17 
AnswerRe: Base of Registry.LocalMachine does not work Pin
Andrew Morpeth5-Jan-15 8:07
memberAndrew Morpeth5-Jan-15 8:07 
GeneralMy vote of 5 Pin
datdit3-Nov-14 4:52
memberdatdit3-Nov-14 4:52 
QuestionCaps in Registry changed from .ToUpper Pin
actualmanx21-Sep-14 4:31
memberactualmanx21-Sep-14 4:31 
QuestionGet default value ? Pin
Wrangly5-Jun-14 3:48
memberWrangly5-Jun-14 3:48 
QuestionI made one modification Pin
Mike Magill23-Jan-14 6:39
memberMike Magill23-Jan-14 6:39 
SuggestionDWORDs and other stuff Pin
James McCullough20-Oct-13 13:40
memberJames McCullough20-Oct-13 13:40 
GeneralMy vote of 5 Pin
Sampath Lokuge29-Sep-13 2:47
memberSampath Lokuge29-Sep-13 2:47 
GeneralMy vote of 5 Pin
Renju Vinod15-Jul-13 20:24
professionalRenju Vinod15-Jul-13 20:24 
QuestionThanks for the utility Pin
arvindps3-Jul-13 19:37
memberarvindps3-Jul-13 19:37 
GeneralMy vote of 5 Pin
leozes3-Jun-13 11:35
memberleozes3-Jun-13 11:35 
GeneralMy vote of 5 Pin
FlyntMD18-May-13 10:30
memberFlyntMD18-May-13 10:30 
QuestionDoes anyone else experienced this strange behavior? Pin
Oscar Miras4-Apr-13 1:53
memberOscar Miras4-Apr-13 1:53 
AnswerRe: Does anyone else experienced this strange behavior? Pin
jprapp25-Apr-13 2:54
memberjprapp25-Apr-13 2:54 
GeneralRe: Does anyone else experienced this strange behavior? Pin
cw229013-Jul-15 6:05
membercw229013-Jul-15 6:05 
QuestionNice but a Q ? Pin
Wrangly28-Feb-13 3:23
memberWrangly28-Feb-13 3:23 
GeneralMy vote of 5 Pin
sadmonew31-Dec-12 7:04
membersadmonew31-Dec-12 7:04 
QuestionClose method ? Pin
r0seBa20-Dec-12 4:10
memberr0seBa20-Dec-12 4:10 
AnswerRe: Close method ? Pin
ahmd04-Apr-13 14:36
memberahmd04-Apr-13 14:36 
QuestionRe:Read, write and delete from registry with C# Pin
guruetech1-Nov-12 20:27
memberguruetech1-Nov-12 20:27 
GeneralMy vote of 5 Pin
Mohan Tangella9-Sep-12 20:04
memberMohan Tangella9-Sep-12 20:04 
Questionwrite and delete from registry with C# Pin
Shwe Nann Thu14-Aug-12 8:08
memberShwe Nann Thu14-Aug-12 8:08 
Generalexcellent Pin
Gun Gun Febrianza14-Aug-12 6:41
memberGun Gun Febrianza14-Aug-12 6:41 
GeneralMy vote of 5 Pin
Gun Gun Febrianza14-Aug-12 6:40
memberGun Gun Febrianza14-Aug-12 6:40 
GeneralThanks Pin
NMathur6-Aug-12 20:38
memberNMathur6-Aug-12 20:38 
GeneralMy vote of 5 Pin
NMathur6-Aug-12 20:38
memberNMathur6-Aug-12 20:38 
Generalthank you Pin
Paolo Bashir Argenton2-Jun-12 4:46
memberPaolo Bashir Argenton2-Jun-12 4:46 
GeneralMy vote of 5 Pin
datdit21-Feb-12 5:38
memberdatdit21-Feb-12 5:38 
QuestionLicencing Pin
Nutter4Ever14-Feb-12 10:57
memberNutter4Ever14-Feb-12 10:57 
QuestionRegistry.CurrentUser stores under HKEY_USERS instead of HKEY_CURRENT_USER for Server application Pin
masteryoda2130-Nov-11 7:49
membermasteryoda2130-Nov-11 7:49 
AnswerRe: Registry.CurrentUser stores under HKEY_USERS instead of HKEY_CURRENT_USER for Server application Pin
masteryoda2113-Dec-11 10:43
membermasteryoda2113-Dec-11 10:43 
GeneralGood article Pin
joyichantg13-Jul-11 21:39
memberjoyichantg13-Jul-11 21:39 
GeneralLocalMachine does not exist in namespace Pin
masteryoda219-May-11 11:27
membermasteryoda219-May-11 11:27 
GeneralRe: LocalMachine does not exist in namespace Pin
Member 825906622-Sep-11 5:15
memberMember 825906622-Sep-11 5:15 
GeneralRe: LocalMachine does not exist in namespace Pin
masteryoda2130-Nov-11 7:52
membermasteryoda2130-Nov-11 7:52 
GeneralThank you Pin
pablogrs31-Jan-11 5:14
memberpablogrs31-Jan-11 5:14 
QuestionAccess to the registry key is denied Pin
TintinBD19-Oct-10 2:49
memberTintinBD19-Oct-10 2:49 
AnswerRe: Access to the registry key is denied Pin
Member 865196827-Jun-12 1:04
memberMember 865196827-Jun-12 1:04 
GeneralMy vote of 5 Pin
TintinBD19-Oct-10 2:45
memberTintinBD19-Oct-10 2:45 
QuestionString only??? Pin
Jacob1737418241-Sep-10 10:59
memberJacob1737418241-Sep-10 10:59 
AnswerRe: String only??? Pin
yuan rahman5-Sep-10 0:55
memberyuan rahman5-Sep-10 0:55 
GeneralStrings Only Pin
alan934-Mar-10 7:03
memberalan934-Mar-10 7:03 
GeneralProblem for creating Registry in vista operating system Pin
nehasingh0981218-Feb-10 20:10
membernehasingh0981218-Feb-10 20:10 
GeneralVery good code Pin
NarendraSinghJTV22-Jan-10 17:57
memberNarendraSinghJTV22-Jan-10 17:57 
GeneralOpenSubKey() with write access Pin
rcgreen29-Oct-09 12:33
memberrcgreen29-Oct-09 12:33 
QuestionAccessing the Registry Remotly? Pin
moh.kanaan6-Jul-09 14:05
membermoh.kanaan6-Jul-09 14:05 
Questionhi:problem Pin
Arsineh Boodaghian1-May-09 0:37
memberArsineh Boodaghian1-May-09 0:37 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150728.1 | Last Updated 18 Dec 2002
Article Copyright 2002 by Francesco Natali
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid