Skip to content

Instantly share code, notes, and snippets.

@mkropat
Last active December 18, 2023 17:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkropat/abf0f1235f0c76034733 to your computer and use it in GitHub Desktop.
Save mkropat/abf0f1235f0c76034733 to your computer and use it in GitHub Desktop.
Simple Windows Registry interface
public interface IKeyValueStore
{
T Read<T>(string key);
void Write<T>(string key, T value);
}
public class RegistryKeyValueStore : IKeyValueStore
{
readonly RegistryHive _hive;
readonly string _regPath;
public RegistryKeyValueStore(string packageName, string vendorName = null, RegistryHive hive = RegistryHive.CurrentUser)
{
_hive = hive;
_regPath = string.IsNullOrEmpty(vendorName)
? Path.Combine("Software", packageName)
: Path.Combine("Software", vendorName, packageName);
}
public T Read<T>(string key)
{
using (var root = OpenRoot())
using (var regKey = root.OpenSubKey(_regPath))
{
return regKey == null
? default
: CoerceToType<T>(regKey.GetValue(key));
}
}
T CoerceToType<T>(object value)
{
var type = typeof(T);
var targetType = type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)
? Nullable.GetUnderlyingType(type)
: type;
if (value == null)
return default;
else if (targetType.IsEnum)
return Enum.IsDefined(targetType, value)
? (T)Enum.Parse(targetType, value as string)
: default;
else
return (T)Convert.ChangeType(value, targetType);
}
public void Write<T>(string key, T value)
{
using (var root = OpenRoot())
using (var subkey = root.CreateSubKey(_regPath))
{
switch (value)
{
case bool v:
subkey.SetValue(key, v, RegistryValueKind.DWord);
break;
default:
subkey.SetValue(key, value);
break;
}
}
}
RegistryKey OpenRoot()
{
return RegistryKey.OpenBaseKey(_hive, RegistryView.Default);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment