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.