Saturday, August 26, 2006

Working with the registry

Opening a subkey:

string subKey = @"Software\Play\WindowPos";
RegistryKey key = Registry.CurrentUser.OpenSubKey(subKey, true);

Creating a subkey:

key = Registry.CurrentUser.CreateSubKey(subKey);

The second parameter specifies whether the key is writable or not.

Getting a value:
  • either by using the static method of the Registry class (in this case, the full registry path must be specified):

    Registry.GetValue(Registry.CurrentUser.Name + @"\" + subKey, "X", 300)
  • by using the curent key (relative path):

    object theValue = key.GetValue("X");
Storing a value:

key.SetValue("X", 123);

Storing/Getting an array of strings:

string[] array = new string[2] { "asd", "dfg" };
k.SetValue("myArray", array, RegistryValueKind.MultiString);
object readArray = k.GetValue("myArray");

Comments:
  1. Use Flush() or Close() to commit changes of the registry key.
  2. Other functions of the RegistryKey class: DeleteSubkeyTree(), DeleteValue(), string[] GetSubKeyNames(), GetSubKeyValues().

No comments: