Working with System Registry by satyasmiles


Introduction:

   Windows Registry is a central database for application configuration settings and other information required by the applications.

 

Actually there is nothing else you can do with Windows Registry besides reading its data and write data to it  In this small article, I’ll give you a idea how to read, write and delete Windows Registry.

 

Registry  Operations in C#:

   The Windows Registry is a data repository that exists on each computer in Windows operating systems. Both the system and application programs use this repository to store information needed at runtime. For example, the system stores file associations (the applications or command lines associated with each known file extension) in the Registry. Applications often use the Registry to store information such as users’ option settings and data file pathnames.
   The system reads the Registry into memory at bootup. This memory image then serves as a working copy for the system. When the system is shut down, it persists the current Registry to disk. The Registry is stored in several files. The location and organization of these files depends on the version of Windows. For example, in Windows 2000, the Registry is stored in a number of files located in the %SystemRoot%System32Config folder, whereas in Windows 95, the Registry is contained in user.dat and system.dat, which are hidden system files in the Windows folder. In all cases, these files must not be edited directly. Changes to the Registry can be made only programmatically or by using a special Registry editor application.

Structure of the Registry

   The Registry has a hierarchical structure, like the folders on a disk volume. The root is not used directly, but instead holds six top-level branches, or hives. The hives are HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CURRENT_CONFIG, and HKEY_DYN_DATA. These hives are described below.
Hive
Description
HKEY_CLASSES_ROOT
The system information store that allows application software to run. This hive contains the mappings between ProgID and ClassID used by COM, as well as file associations and program launching information.
HKEY_CURRENT_USER
This refers to (like a symbolic link) the section in the HKEY_USERS hive relevant to the currently logged on user.
HKEY_LOCAL_MACHINE
This is the core system information store. It contains system device information under its HARDWARE key, basic system information under the SYSTEM key, and application-specific information under the SOFTWARE key.
HKEY_USERS
This hive contains a key for each user with an account on the machine, as well as a default user. Users’ preferences and UI settings are stored here.
HKEY_CURRENT_CONFIG
This is like a symbolic link to the section in HKEY_LOCAL_MACHINEHARDWARE for the current hardware profile.
HKEY_DYN_DATA
This hive may or may not be present. If it is, then it contains information related to the current plug-and-play devices on the machine.
   Each hive contains a number of keys. Registry keys are the basic data structure for the Registry. A Registry key acts like a subfolder, holding additional levels of subkeys, as well as values—name/value pairs that are used to hold the actual information.
 

Registry Data Types

   The data that is stored in a Registry value can be represented by one of a number of data types. The most common are number, text string, and direct binary data. These are implemented through five data types: REG_DWORD, REG_BINARY, REG_SZ, REG_MULTI_SZ, or REG_EXPAND_SZ. These data types are described below:
Type
Description
REG_DWORD
A double word (four-byte) number. Stores numerical data and is used for Boolean values, with 0 being false (meaning “no” or “off,” for example), and 1 being true.
REG_BINARY
Stores binary data. These values appear in hexadecimal format when viewed in a Registry editor.
REG_SZ
Stores information as a plain text string.
REG_MULTI_SZ
Stores multiple null-terminated strings. Used to store lists and arrays.
REG_EXPAND_SZ
Stores an environment string variable, such as “%SystemRoot%”.
    The application then reads and writes Registry values containing the desired data. By convention, application programs will normally use subkeys relative to HKEY_LOCAL_MACHINESOFTWARE for storing their data.
   In the Microsoft .NET Framework, the Registry class provides complete access to the Windows Registry. The Registry hives are exposed as seven read-only root RegistryKey instances: CurrentUser, LocalMachine, ClassesRoot, Users, PerformanceData, CurrentConfig, and DynData. Include a reference to the Microsoft.Win32 namespace to instantiate these classes.
 

Getting a Registry Key Reference

  Example 1 illustrates a method for creating or opening a specified Registry key. The method accepts two string arguments: a base key name, followed by a subkey name. It will return an instance of the RegistryKey class, which will be null if an exception occurs.
  First, the OpenSubKey method of the Registry.LocalMachine instance is used to attempt to get a reference to the specified base key. The second argument of this method is a Boolean value that specifies whether or not write access to the key is required. If the desired base key cannot be found, then the method will attempt to create one.
   Next, the CreateSubKey method of Registry.LocalMachine is used to get a reference to the desired subkey. CreateSubKey will return a reference to a specified key if it already exists or to a newly created one if it does not. Finally, the method returns the reference to the key, which can be checked against null for success.

Example 1—Method for Creating or Opening a Registry Key

public static RegistryKey GetKey(string baseKey, string subKey) {

 RegistryKey key;

 /* — open a Base Key — */

 try {

  key = Registry.LocalMachine.OpenSubKey(baseKey, true);

  if (key == null) {

   key = Registry.LocalMachine.CreateSubKey(baseKey);

  }

  else {

   Console.WriteLine(“Base key resolved”);

  }

 }

 catch (Exception e)

 {

                  return null;

 }

 

 /* — create a Sub Key — */

 try {

  key = Registry.LocalMachine.CreateSubKey(baseKey +”\” + subKey);

   if (key == null) {

   throw(new Exception(“Error creating SubKey”));

  }

  else {

   Console.WriteLine(“Subkey Done”);

  }

 }

 catch (Exception e) {

  return null;

 }

 return key;

}

 
  See next page for storing and retrieving values from registry..
 

Storing Registry Values:

   Storing and retrieving Registry values is quite simple.

Example 2 illustrates the syntax for writing a value to the Registry using the SetValue method of the RegistryKey class. There is no separate method for creating a value. If the value already exists, then SetValue will update it. If it does not already exist, it will automatically be created.

Example 2—Example of Creating or Setting a Registry Value

public static void SetValue(RegistryKey key,  string valueName,   object valueValue) {

 try {

  // In production code, you would validate the arguments

  key.SetValue(valueName, valueValue);

  Console.WriteLine(“Key value set OK”);

 }

 catch (Exception e) {

  Console.WriteLine(“Error in setting key value: {0}”,   e.ToString());

 }

}

   The valueName argument can be set either to null or to an empty string to set the default value for the specified key.

   As far as I know, there is currently no way to specify the Registry data type of the value being passed. The argument is apparently interpreted when passed and classified as either numeric, binary, or string. All string arguments are interpreted to be of the type REG_SZ, so parsing and evaluating REG_MULTI_SZ and REG_EXPAND_SZ data on Registry reads must be done manually (see the ExpandEnvironmentVariables method of the Environment class for additional information).

Retrieving Registry Values

  Use the GetValue method of the RegistryKey class to read a value from the Registry. GetValue is an overloaded method with two forms. The simplest is
public object GetValue(string name);
   This method accepts a string parameter that specifies the name of the Registry value to read. It returns an object containing the requested value or null if the value does not exist. Example 3 is an example of how to use GetValue to return a string containing a specified value.

Example 3—Example of Reading a Known Registry Value

public static string GetTest(string SubKey, string Name)

{

 string ds = null;

 RegistryKey key = Registry.LocalMachine.OpenSubKey(“SOFTWARE\HSL\” + SubKey);

if (key != null)

{

 ds = key.GetValue(Name).ToString();

 }

 return ds; 

}

The other form of the GetValue method is

public object GetValue(string name, object defaultValue);
   This form of the method allows you to pass a second argument containing an object that specifies a default value to return if name does not exist.
   Note that the Windows Registry is not, by itself, a secure storage mechanism. Information stored in the Registry is available to other applications and through user identities other than the ones used to store it. Sensitive information, such as passwords, must be encrypted before being written to the Registry.