Created
October 12, 2017 08:57
-
-
Save distantcam/6ea5ef35072538f8695e25dc5214e108 to your computer and use it in GitHub Desktop.
Simple config class
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
public static class SimpleConfig | |
{ | |
static string configFilePath; | |
public static void InitializeInLocalApplicationData(string name) | |
{ | |
Initialize(Path.Combine( | |
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), | |
name, | |
"config.xml" | |
)); | |
} | |
public static void InitializeInApplicationData(string name) | |
{ | |
Initialize(Path.Combine( | |
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), | |
name, | |
"config.xml" | |
)); | |
} | |
public static void InitializeInCommonApplicationData(string name) | |
{ | |
Initialize(Path.Combine( | |
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), | |
name, | |
"config.xml" | |
)); | |
} | |
public static void Initialize(string configPath) | |
{ | |
configFilePath = configPath; | |
Directory.CreateDirectory(Path.GetDirectoryName(configFilePath)); | |
if (!File.Exists(configFilePath)) | |
{ | |
File.WriteAllText(configFilePath, @"<config />"); | |
} | |
} | |
public static void OpenConfig() | |
{ | |
Process.Start(configFilePath); | |
} | |
public static string GetValue(string key, string defaultValue = "") | |
{ | |
var config = XDocument.Load(configFilePath).Root; | |
var node = config.Descendants(key).FirstOrDefault(); | |
if (node == null) | |
{ | |
return defaultValue; | |
} | |
return node.Value; | |
} | |
public static void SetValue(string key, string value) | |
{ | |
var config = XDocument.Load(configFilePath).Root; | |
var node = config.Descendants(key).FirstOrDefault(); | |
if (node == null) | |
{ | |
node = new XElement(key); | |
config.Add(node); | |
} | |
node.Value = value; | |
config.Save(configFilePath); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment