Skip to content

Instantly share code, notes, and snippets.

@distantcam
Created October 12, 2017 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save distantcam/6ea5ef35072538f8695e25dc5214e108 to your computer and use it in GitHub Desktop.
Save distantcam/6ea5ef35072538f8695e25dc5214e108 to your computer and use it in GitHub Desktop.
Simple config class
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