17.4 Access the Windows Registry


Problem

You need to read information from, or write information to, the Windows registry.

Solution

Use the Microsoft.Win32.Registry class to obtain a Microsoft.Win32.RegistryKey object that represents the root key of a registry hive. Use the members of this RegistryKey object to navigate through and enumerate the registry key hierarchy as well as to read, modify, and create registry keys and values.

Discussion

It isn't possible to gain direct access to keys and values contained in the registry. You must first obtain a RegistryKey object that represents a base-level key and navigate through the hierarchy of RegistryKey objects to the key you need. The Registry class implements a set of seven static fields that return RegistryKey objects representing base level registry keys; Table 17-3 describes the registry location to where each of these fields maps.

Table 17.3: Static Fields of the Registry Class

Field

Registry Mapping

ClassesRoot

HKEY_CLASSES_ROOT

CurrentConfig

HKEY_CURRENT_CONFIG

CurrentUser

HKEY_CURRENT_USER

DynData

HKEY_DYN_DATA

LocalMachine

HKEY_LOCAL_MACHINE

PerformanceData

HKEY_PERFORMANCE_DATA

Users

HKEY_USERS

Tip  

The static method RegistryKey.OpenRemoteBaseKey allows you to open a registry base key on a remote machine. See the .NET Framework SDK documentation for details of its use.

Once you have the base level RegistryKey object, you must navigate to the key with which you want to work. To support navigation, the RegistryKey class allows you to do the following:

  • Get the number of immediate subkeys using the SubKeyCount property.

  • Get a string array containing the names of all subkeys using the GetSubKeyNames method.

  • Get a RegistryKey reference to a subkey using the OpenSubKey method. The OpenSubKey method provides two overloads: the first opens the named key as read-only; the second accepts a bool argument that if true will open a writable RegistryKey object.

Once you obtain a RegistryKey object that represents the registry key you need, you can create, read, update, and delete subkeys and values using the methods listed in Table 17.4. Methods that modify the contents of the key require you to have a writable RegistryKey object.

Table 17.4: RegistryKey Methods to Create, Read, Update, and Delete Registry Keys and Values

Method

Description

CreateSubKey

Creates a new subkey with the specified name and returns a writable RegistryKey object. If the specified subkey already exists, CreateSubKey returns a writable reference to the existing subkey.

DeleteSubKey

Deletes the subkey with the specified name, which must be empty of subkeys (but not values); otherwise , a System.InvalidOperationException is thrown.

DeleteSubKeyTree

Deletes the subkey with the specified name along with all of its subkeys.

DeleteValue

Deletes the value with the specified name from the current key.

GetValue

Returns the value with the specified name from the current key. The value is returned as an object , which you must cast to the appropriate type. The simplest form of GetValue returns null if the specified value doesn't exist. An overload allows you to specify a default value to return (instead of null ) if the named value doesn't exist.

GetValueNames

Returns a string array containing the names of all values in the current registry key.

SetValue

Creates (or updates) the value with the specified name. You can't specify the registry data type used to store the value; SetValue chooses the data type automatically based on the type of data stored.

The RegistryKey class implements IDisposable; you should call the IDisposable.Dispose method to free operating system resources when you have finished with the RegistryKey object.

The RegistryExample class shown here takes a single command-line argument and recursively searches the CurrentUser hive of the registry looking for keys with names matching the supplied argument. When RegistryExample finds a match, it displays all string type values contained in the key to the console. The RegistryExample class also maintains a usage count in the registry key HKEY_CURRENT_USER\RegistryExample.

 using System; using Microsoft.Win32; public class RegistryExample {     public static void Main(String[] args) {         if (args.Length > 0) {             // Open the CurrentUser base key.             using(RegistryKey root = Registry.CurrentUser) {                 // Update the usage counter.                 UpdateUsageCounter(root);                 // Search recursively through the registry for any keys                 // with the specified name.                 SearchSubKeys(root, args[0]);             }         }         // Wait to continue.         Console.WriteLine("Main method complete. Press Enter.");         Console.ReadLine();     }     public static void UpdateUsageCounter(RegistryKey root) {         // Create the key where the usage count is stored, or obtain a         // reference to an existing key.         RegistryKey countKey = root.CreateSubKey("RegistryExample");         // Read the current usage count value and specify a default value         // of 0 (zero). Cast the Object to Int32, and assign to an int.         int count = (Int32)countKey.GetValue("UsageCount", 0);         // Write the incremented usage count back to the registry, or          // create a new value if it does not yet exist.         countKey.SetValue("UsageCount", ++count);     }     public static void SearchSubKeys(RegistryKey root, String searchKey) {         // Loop through all subkeys contained in the current key.         foreach (string keyname in root.GetSubKeyNames()) {             try {                 using (RegistryKey key = root.OpenSubKey(keyname)) {                     if (keyname == searchKey) PrintKeyValues(key);                     SearchSubKeys(key, searchKey);                 }             } catch (System.Security.SecurityException) {                 // Ignore SecurityException for the purpose of the example.                 // Some subkeys of HKEY_CURRENT_USER are secured and will                 // throw a SecurityException when opened.             }         }     }     public static void PrintKeyValues(RegistryKey key) {         // Display the name of the matching subkey and the number of         // values it contains.         Console.WriteLine("Registry key found : {0} contains {1} values",             key.Name, key.ValueCount);         // Loop through the values and display.          foreach (string valuename in key.GetValueNames()) {             if (key.GetValue(valuename) is String) {                 Console.WriteLine("  Value : {0} = {1}",                      valuename, key.GetValue(valuename));             }         }     }  } 

The example will display output similar to the following when executed using the command RegistryExample Environment on a machine running Windows XP.

 Registry key found : HKEY_CURRENT_USER\Environment contains 4 values   Value : TEMP = C:\Documents and Settings\Allen\Local Settings\Temp   Value : TMP = C:\Documents and Settings\Allen\Local Settings\Temp   Value : LIB = C:\Dev\Microsoft Visual Studio .NET 2003\SDK\v1.1\Lib\   Value : INCLUDE = C:\Dev\Microsoft Visual Studio .NET 2003\SDK\v1.1\include\ 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net