In Registry schreiben und lesen

Nachfolgend ein kurzes Code-Snippet zum lesen und schreiben in die Registry.

Viel SpaƟ damit!

[sourcecode language=“csharp“]
/// <summary>
/// Writes the registry.
/// </summary>
/// <param name="parentKey">The parent key.</param>
/// <param name="subKey">The sub key.</param>
/// <param name="valueName">Name of the value.</param>
/// <param name="value">The value.</param>
public static void WriteRegistry(RegistryKey parentKey, String subKey, String valueName, Object value)
{
RegistryKey key;
Console.WriteLine(@"parentKey: " + parentKey.ToString());
Console.WriteLine(@"subKey: " + subKey);

try
{
key = parentKey.OpenSubKey(subKey, true);
if (key == null) //If the key doesn’t exist.
key = parentKey.CreateSubKey(subKey);

//Set the value.
key.SetValue(valueName, value);

Console.WriteLine(@"Value:{0} for {1} is successfully written.", value, valueName);
}
catch (Exception e)
{
Console.WriteLine(@"Error occurs in WriteRegistry: " + e.Message + "(" + e.Source + ")");
}
}

/// <summary>
/// Reads the registry.
/// </summary>
/// <param name="parentKey">The parent key.</param>
/// <param name="subKey">The sub key.</param>
/// <param name="valueName">Name of the value.</param>
static void ReadRegistry(RegistryKey parentKey, String subKey, String valueName)
{
RegistryKey key;

try
{
key = parentKey.OpenSubKey(subKey, true);
if (key == null) //If the key doesn’t exist.
throw new Exception("The registry key doesn’t exist");

//Get the value.
var value = key.GetValue(valueName);

Console.WriteLine(@"Value:{0} for {1} is successfully retrieved.", value, valueName);
}
catch (Exception e)
{
Console.WriteLine(@"Error occurs in ReadRegistry" + e.Message);
}
}
[/sourcecode]

Cheers,
Chris aka. diesmal kein Roman!

Leave a reply