Skip to content

Instantly share code, notes, and snippets.

@mrstebo
Created June 2, 2020 11:18
Show Gist options
  • Select an option

  • Save mrstebo/b2cd3939f5b64ccfa573b4383edc5d3d to your computer and use it in GitHub Desktop.

Select an option

Save mrstebo/b2cd3939f5b64ccfa573b4383edc5d3d to your computer and use it in GitHub Desktop.
c-net-registry-based-configuration-base-class-6
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
namespace ns_stebo
{
public abstract class RegistryConfig
{
public RegistryHive Hive
{
get;
private set;
}
public string RootKey
{
get;
private set;
}
protected RegistryConfig(RegistryHive hive, string rootKey)
{
Hive = hive;
RootKey = rootKey;
}
public bool Exists(string key)
{
return GetValue<object>(key, null) != null;
}
protected T GetValue<T>(string key, T defaultValue)
{
try
{
using (var rk = GetRegistryKey())
{
using (var sk = rk.CreateSubKey(RootKey))
{
var o = rk.GetValue(key, null);
if (o == null)
SetValue(key, (o = defaultValue));
return (T)o;
}
}
}
catch (Exception ex)
{
Trace.TraceError("Failed to get value for {0}: {1}", key, ex);
throw;
}
}
protected void SetValue<T>(string key, T value)
{
try
{
using (var rk = GetRegistryKey())
{
using (var sk = rk.CreateSubKey(RootKey))
{
rk.SetValue(key, value);
}
}
}
catch (Exception ex)
{
Trace.TraceError("Failed to set value for {0}: {1}", key, ex);
throw;
}
}
protected RegistryKey GetRegistryKey()
{
switch (Hive)
{
case RegistryHive.ClassesRoot:
return Registry.ClassesRoot;
case RegistryHive.CurrentConfig:
return Registry.CurrentConfig;
case RegistryHive.CurrentUser:
return Registry.CurrentUser;
case RegistryHive.DynData:
return Registry.DynData;
case RegistryHive.LocalMachine:
return Registry.LocalMachine;
case RegistryHive.PerformanceData:
return Registry.PerformanceData;
case RegistryHive.Users:
return Registry.Users;
}
throw new NullReferenceException("Unable to get registry key: " + Hive);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment