using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Drawing; using System.IO; using System.Windows.Forms; using Microsoft.Win32; namespace Common { public static class ApplicationSettings { public static string variable; public static void SetDefault() { variable = ""; } public static void LoadFromRegistry(string regSubKey = "") { RegistryKey regKey = Application.UserAppDataRegistry.OpenSubKey(regSubKey); if (regKey == null) return; variable = regKey.GetValueString("Variable", variable); } public static void SaveToRegistry(string regSubKey = "") { RegistryKey regKey = Application.UserAppDataRegistry.OpenSubKey(regSubKey, true); if (regKey == null) regKey = Application.UserAppDataRegistry.CreateSubKey(regSubKey); regKey.SetValueString("Variable", variable); } public static void CopyRegistry(RegistryKey src, RegistryKey dst) { // Copy the values foreach (var name in src.GetValueNames()) { dst.SetValue(name, src.GetValue(name), src.GetValueKind(name)); } // Copy the subkeys foreach (var name in src.GetSubKeyNames()) { using (var srcSubKey = src.OpenSubKey(name, false)) { var dstSubKey = dst.CreateSubKey(name); CopyRegistry(srcSubKey, dstSubKey); } } } private static bool IsValidVersion(string version) { return Regex.Match(version, "^(\\d+\\.){3}(\\d+)$").Success; } public static void UpgradeRegistrySettings() { RegistryKey regKey = Application.UserAppDataRegistry.OpenSubKey("", true); if (regKey == null) regKey = Application.UserAppDataRegistry.CreateSubKey(""); if (regKey.GetValue("Upgraded") == null) { string parentKey = Application.UserAppDataRegistry.Name.Substring(0, Application.UserAppDataRegistry.Name.LastIndexOf('\\')); parentKey = parentKey.Substring(parentKey.IndexOf('\\') + 1); RegistryKey parentRegKey = Registry.CurrentUser.OpenSubKey(parentKey, false); if (parentRegKey != null) { List subKeys = new List(parentRegKey.GetSubKeyNames()); var versions = new List(); foreach (var key in subKeys) { if (IsValidVersion(key) && ("HKEY_CURRENT_USER\\" + parentKey + '\\' + key + '\\' != regKey.ToString())) versions.Add(new Version(key)); } versions.Sort(); versions.Reverse(); if (versions.Count > 0) { RegistryKey srcKey = Registry.CurrentUser.OpenSubKey(parentKey + '\\' + versions[0].ToString()); CopyRegistry(srcKey, regKey); } } regKey.SetValue("Upgraded", true); } } } }