SIGN UP MEMBER LOGIN:    
ARTICLE

Reading and Writing to the Registry

Posted by Scott Newman Articles | Current Affairs February 28, 2001
This is a class that both reads and writes to the registry that I made while converting some applications to use C#.
Reader Level:

Introduction

This is a class that both reads and writes to the registry that I made while converting some applications to use C#.  This registry utility only reads and writes strings at the moment, but I'm sure if you wanted to read or write binary data you could modify the existing code to suit your needs.

One thing to note about my programming style (which most of my colleagues detest) is that my function will return a zero if successful.  I just find it easier to use constants to define errors and return them so I can be more accurate with my error handling.

Functions

The function WriteToReg takes an enum indicating the registry root to use.  The second argument is the path to the registry key that you want to write to.  The third parameter is the Key name, and the fourth the key value.  It should be noted that this function will create the registry key if it does not exist already.

The ReadFromRegistry function takes an enum indicating the registry root to use.  The second argument is the path to the registry key, the third is the name of the key from which you want to retrieve the value, and the fourth is a default value to return if the key does not exist.

Source Code

namespace RFG
{
using System;
using Microsoft.Win32;
public class RegUtil
{
public const int REG_ERR_NULL_REFERENCE = 12;
public const int REG_ERR_SECURITY = 13;
public const int REG_ERR_UNKNOWN = 14;
public enum REGUTIL_KEYS
{
HKCR = 0,
HKCU = 1,
HKLM = 2,
HKU = 3,
HKCC = 4
}
char[] Delimit = {'\x005c'}; //Hex for '\'
public RegUtil()
{}
public int WriteToReg(REGUTIL_KEYS Key, string RegPath, string KeyName, string KeyValue)
{
string[] RegString;
RegString = RegPath.Split(Delimit);
//First item of array will be the base key, so be carefull iterating below
RegistryKey[] RegKey = new RegistryKey[RegPath.Length + 1];
//Returns proper key -- Will Default to hkey_current_user
RegKey[0] = SelectKey(Key);
for(int i = 0;i < RegString.Length;i++)
{
RegKey[i + 1] = RegKey[i].OpenSubKey(RegString[i],
true);
//If key does not exist, create it. This logic usually suits my needs, but
//you may change it if you wish.
if (RegKey[i + 1] == null)
{
RegKey[i + 1] = RegKey[i].CreateSubKey(RegString[i]);
}
}
//Write the value to the registry. If fail, return the constant values defined at the beginning of the class
try
{
RegKey[RegString.Length].SetValue(KeyName, KeyValue);
}
catch (System.NullReferenceException)
{
return REG_ERR_NULL_REFERENCE;
}
catch (System.UnauthorizedAccessException)
{
return REG_ERR_SECURITY;
}
return 0;
}
//----------- End WriteToReg ----------------------------
///
<summary>
///
/// </summary>
/// <param name="Key"> </param>
/// <param name="RegPath"> </param>
/// <param name="KeyName"> </param>
/// <param name="DefaultValue"> </param>
public string ReadFromRegistry(REGUTIL_KEYS Key, string RegPath, string KeyName, string DefaultValue)
{
string[] RegString;
string Result = "";
RegString = RegPath.Split(Delimit);
//First item of array will be the base key, so be carefull iterating below
RegistryKey[] RegKey = new RegistryKey[RegPath.Length + 1];
//Returns proper key -- Will Default to HKEY_CURRENT_USER
RegKey[0] = SelectKey(Key);
for(int i = 0;i < RegString.Length;i++)
{
RegKey[i + 1] = RegKey[i].OpenSubKey(RegString[i]);
if (i == RegString.Length - 1 )
{
Result = (
string)RegKey[i + 1].GetValue(KeyName, DefaultValue);
}
}
return Result;
}
// -------------- End ReadFromRegistry -------------------
//Separated for cleanliness
private RegistryKey SelectKey(REGUTIL_KEYS Key)
{
switch (Key)
{
case REGUTIL_KEYS.HKCR:
return Registry.ClassesRoot;
case REGUTIL_KEYS.HKCU:
return Registry.CurrentUser;
case REGUTIL_KEYS.HKLM:
return Registry.LocalMachine;
case REGUTIL_KEYS.HKU:
return Registry.Users;
case REGUTIL_KEYS.HKCC:
return Registry.CurrentConfig;
default:
return Registry.CurrentUser;
}
}
//---------------- End SelectKey --------------------------
}// end Class
} // End Namespace

Login to add your contents and source code to this article
share this article :
post comment
 
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor