Here is the working code I have developed to both read and write ONLY the 32-bit registry. It works in both 32-bit and 64-bit applications. The 'read' call updates the registry if the value is not set, but it is very obvious how to remove that. It requires .Net 4.0, and uses the OpenBaseKey/OpenSubKey methods.
I currently use it to allow a 64-bit background service and a 32-bit tray application to access the same registry keys seamlessly.
using Microsoft.Win32;
namespace SimpleSettings
{
public class Settings
{
private static string RegistrySubKey = @"SOFTWARE\BlahCompany\BlahApp";
public static void write(string setting, string value)
{
using (RegistryKey registryView = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
using (RegistryKey registryCreate = registryView.CreateSubKey(RegistrySubKey))
using (RegistryKey registryKey = registryView.OpenSubKey(RegistrySubKey, true))
{
registryKey.SetValue(setting, value, RegistryValueKind.String);
}
}
public static string read(string setting, string def)
{
string output = string.Empty;
using (RegistryKey registryView = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
using (RegistryKey registryCreate = registryView.CreateSubKey(RegistrySubKey))
using (RegistryKey registryKey = registryView.OpenSubKey(RegistrySubKey, false))
{
// Read the registry, but if it is blank, update the registry and return the default.
output = (string)registryKey.GetValue(setting, string.Empty);
if (string.IsNullOrWhiteSpace(output))
{
output = def;
write(setting, def);
}
}
return output;
}
}
}
Usage:
Put this in it's own class file (.cs) and call it as such:
using SimpleSettings;
string mysetting = Settings.read("SETTINGNAME","DEFAULTVALUE");