source: Common/ApplicationSettings.cs

Last change on this file was 10, checked in by chronos, 5 years ago
  • Added: Class for storing values in registry.
File size: 3.4 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Text.RegularExpressions;
6using System.Threading.Tasks;
7using System.Drawing;
8using System.IO;
9using System.Windows.Forms;
10using Microsoft.Win32;
11
12namespace Common
13{
14 public static class ApplicationSettings
15 {
16 public static string variable;
17
18 public static void SetDefault()
19 {
20 variable = "";
21 }
22
23 public static void LoadFromRegistry(string regSubKey = "")
24 {
25 RegistryKey regKey = Application.UserAppDataRegistry.OpenSubKey(regSubKey);
26 if (regKey == null) return;
27
28 variable = regKey.GetValueString("Variable", variable);
29 }
30
31 public static void SaveToRegistry(string regSubKey = "")
32 {
33 RegistryKey regKey = Application.UserAppDataRegistry.OpenSubKey(regSubKey, true);
34 if (regKey == null) regKey = Application.UserAppDataRegistry.CreateSubKey(regSubKey);
35
36 regKey.SetValueString("Variable", variable);
37 }
38
39 public static void CopyRegistry(RegistryKey src, RegistryKey dst)
40 {
41 // Copy the values
42 foreach (var name in src.GetValueNames())
43 {
44 dst.SetValue(name, src.GetValue(name), src.GetValueKind(name));
45 }
46
47 // Copy the subkeys
48 foreach (var name in src.GetSubKeyNames())
49 {
50 using (var srcSubKey = src.OpenSubKey(name, false))
51 {
52 var dstSubKey = dst.CreateSubKey(name);
53 CopyRegistry(srcSubKey, dstSubKey);
54 }
55 }
56 }
57
58 private static bool IsValidVersion(string version)
59 {
60 return Regex.Match(version, "^(\\d+\\.){3}(\\d+)$").Success;
61 }
62
63 public static void UpgradeRegistrySettings()
64 {
65 RegistryKey regKey = Application.UserAppDataRegistry.OpenSubKey("", true);
66 if (regKey == null) regKey = Application.UserAppDataRegistry.CreateSubKey("");
67 if (regKey.GetValue("Upgraded") == null)
68 {
69 string parentKey = Application.UserAppDataRegistry.Name.Substring(0, Application.UserAppDataRegistry.Name.LastIndexOf('\\'));
70 parentKey = parentKey.Substring(parentKey.IndexOf('\\') + 1);
71 RegistryKey parentRegKey = Registry.CurrentUser.OpenSubKey(parentKey, false);
72 if (parentRegKey != null)
73 {
74 List<string> subKeys = new List<string>(parentRegKey.GetSubKeyNames());
75 var versions = new List<Version>();
76 foreach (var key in subKeys)
77 {
78 if (IsValidVersion(key) && ("HKEY_CURRENT_USER\\" + parentKey + '\\' + key + '\\' != regKey.ToString()))
79 versions.Add(new Version(key));
80 }
81 versions.Sort();
82 versions.Reverse();
83
84 if (versions.Count > 0)
85 {
86 RegistryKey srcKey = Registry.CurrentUser.OpenSubKey(parentKey + '\\' + versions[0].ToString());
87 CopyRegistry(srcKey, regKey);
88 }
89 }
90 regKey.SetValue("Upgraded", true);
91 }
92 }
93 }
94}
Note: See TracBrowser for help on using the repository browser.