Just to quickly explain what this is and what it does: it's a config handler that loads a file that has configuration data in INI format, key=value that sort of format. I then just store it all inside a double string dictionary and take items from the dictionary when I need them.
Questions:
- Is my dispose pattern okay? Do I even need to dispose in the first place? I'm still learning about disposing and memory management.
- Should I be locking on the dictionary?
- Am I okay to use LINQ? I recently got told that LINQ slows down your code. Is there any better way to do this? Is the speed much different?
namespace Pitaya.Root.Core.Config
{
internal class ConfigHandler : IDisposable
{
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
private Dictionary<string, string> _configItems;
internal ConfigHandler()
{
_configItems = new Dictionary<string, string>();
LoadConfig("/resources/config/config.ini");
}
internal void LoadConfig(string configFile)
{
try
{
if (!File.Exists(configFile) || FileUtilities.IsFileLocked(new FileInfo(configFile)))
{
Logger.Error("Either your config file couldn't be found, or its open somewhere else.");
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("Error while loading config: " + exception.Message);
Logger.Fatal(exception.StackTrace);
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;
}
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (!disposing)
{
return;
}
_configItems.Clear();
_configItems = null;
}
}
}