Posted by: Cirilo Meggiolaro | 02/13/2009

Tip of the day #122 – Reading and writing keys to the Windows registry

The .NET Framework contains some classes to make your task of read from and write to the Windows registry easy. For those who haven’t programmatically written to or read from the Windows registry think about the registry system as a folder tree where the folders are called sub keys and the “files” are called values.

How to…

  • To create values you need to have an instance of a RegistryKey class that points to the sub key where the new value will be set up;
  • Create sub keys or open existing ones using the CreateSubKey() method;
  • Create a key with the method SetValue();
  • Read values from the registry is pretty much the same but you are going to use the GetValue() method instead.

The following code snippet show how to create a folder under the {HKEY_LOCAL_MACHINE\Software} that represents the company name, a sub key for the company product and some keys with different data types:

/// Creates a registry key object that stores the new key.
Microsoft.Win32.RegistryKey mySoftwareKey;

/// Uses the CreateSubKey method to create the new sub keys.
mySoftwareKey = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(
@”Software\MyCompanyName\MySoftwareName”);

/// Creates some keys with different values
mySoftwareKey.SetValue(“MyKey1”, 1);
mySoftwareKey.SetValue(“MyKey2”, Guid.NewGuid());
mySoftwareKey.SetValue(“MyKey3”, DateTime.Now);
mySoftwareKey.SetValue(“MyKey4”, “This is a string.”);

/// Flushes all the changes to the registry system.
mySoftwareKey.Close();

/// Releases the reference.
mySoftwareKey = null;

The following code snippet reads from the registry all the keys we created on the previous step:

/// Creates a registry key object that stores the new key.
Microsoft.Win32.RegistryKey mySoftwareKey;

/// Uses the CreateSubKey method to open the sub keys.
mySoftwareKey = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(
@”Software\MyCompanyName\MySoftwareName”);

/// Loops through a collection of value names
foreach (string keyName in mySoftwareKey.GetValueNames())
{
    /// Uses the GetValue(string keyName)
    /// method to retrieve the key value.

    Console.WriteLine(“{0}: {1}”, keyName, mySoftwareKey.GetValue(keyName));
}


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: