This class will load a file with INI configuration elements and cache them, it then has a method to get an item from the cache if it needs to.
internal class ConfigHandler
{
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
private Dictionary<string, string> _configItems;
public ConfigHandler()
{
_configItems = new Dictionary<string, string>();
LoadConfig("resources/config/pitaya.ini");
}
internal void LoadConfig(string configFile)
{
try
{
if (!File.Exists(configFile))
{
Logger.Error("Your config file couldn't be found.");
Console.ReadKey(true);
Environment.Exit(0);
}
if (CoreUtilities.IsFileLocked(new FileInfo(configFile)))
{
Logger.Error("Your config file is already open somewhere.");
Console.ReadKey(true);
Environment.Exit(0);
}
_configItems = File.ReadLines(configFile).Where(IsConfigurationLine).Select(line => line.Split('=')).ToDictionary(line => line[0], line => line[1]);
}
catch (Exception exception)
{
Logger.Fatal(exception, "Error while loading config.");
Console.ReadKey(true);
Environment.Exit(0);
}
}
private static bool IsConfigurationLine(string line)
{
return !line.StartsWith("#") && line.Contains("=");
}
internal string GetConfigValueByKey(string key)
{
if (!_configItems.TryGetValue(key, out var value))
{
Logger.Warn("Missing configuration key `" + key + "`");
}
return value;
}
}