Created
March 24, 2023 08:58
-
-
Save japsuu/b4fd2e7092ef67775971579b30f500bf to your computer and use it in GitHub Desktop.
Super simple WinForms config manager. TextBox saving support.
This file contains 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 System.Configuration; | |
public static class Config | |
{ | |
private static Configuration configManager; | |
private static KeyValueConfigurationCollection configuration; | |
// Support lazy loading initialization. | |
private static bool hasInitialized; | |
// Support manual initialization. | |
public static void Initialize() | |
{ | |
CheckInitialization(); | |
} | |
private static void CheckInitialization() | |
{ | |
if (!hasInitialized) | |
InitializeConfig(); | |
} | |
private static void InitializeConfig() | |
{ | |
configManager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); | |
configuration = configManager.AppSettings.Settings; | |
hasInitialized = true; | |
} | |
public static void SaveTextBox(TextBox textBox) | |
{ | |
CheckInitialization(); | |
SaveValue(textBox.Name, textBox.Text); | |
} | |
public static void LoadTextBox(TextBox textBox, string defaultValue) | |
{ | |
CheckInitialization(); | |
string configValue = LoadValue(textBox.Name, defaultValue); | |
textBox.Text = configValue; | |
} | |
/// <summary> | |
/// Saves the given <see cref="value"/> to the config with the given <see cref="key"/>. | |
/// </summary> | |
public static void SaveValue(string key, string value) | |
{ | |
CheckInitialization(); | |
if (TryGetConfigEntry(key, out string _)) | |
configuration[key].Value = value; | |
else | |
configuration.Add(key, value); | |
configManager.Save(ConfigurationSaveMode.Modified); | |
ConfigurationManager.RefreshSection(configManager.AppSettings.SectionInformation.Name); | |
} | |
/// <summary> | |
/// Returns a value from the config with the given <see cref="key"/>. | |
/// Defaults to <see cref="defaultValue"/>. | |
/// </summary> | |
public static string LoadValue(string key, string defaultValue = "") | |
{ | |
CheckInitialization(); | |
if (TryGetConfigEntry(key, out string value)) return value; | |
return defaultValue; | |
} | |
private static bool TryGetConfigEntry(string key, out string value) | |
{ | |
KeyValueConfigurationElement raw = configuration[key]; | |
value = ""; | |
if (raw != null) | |
value = raw.Value; | |
return raw != null && raw.Value != null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment