Created
June 2, 2020 11:18
-
-
Save mrstebo/b2cd3939f5b64ccfa573b4383edc5d3d to your computer and use it in GitHub Desktop.
c-net-registry-based-configuration-base-class-6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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