I have below coded a class that loads information from a file that I select. The file then loads the content of that file in the INI format.
The INI format usually works when each line contains key=value and then each line is split by the = character in the code. It also contains a method for getting the item by key from the dictionary of stored items previously loaded from the file. I wondered if anyone could help me out in finding any way to improve this?
I think its pretty well coded in my eyes, but of course there is always room for improvement.
namespace Hariak_Emulator.Emulator.Core.Config
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NLog;
using Utilities;
internal sealed class ConfigManager : IDisposable
{
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
private Dictionary<string, string> _configItems;
private string _configFile;
public ConfigManager()
{
_configItems = new Dictionary<string, string>();
_configFile = "assets/config/hariak_config.ini";
LoadConfig();
}
private void LoadConfig()
{
try
{
if (!File.Exists(_configFile) || Utilities.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)
{
string value;
if (!_configItems.TryGetValue(key, out value))
{
Logger.Warn("Missing configuration key `" + key + "`");
}
return value;
}
public void Dispose()
{
if (!disposing)
{
return;
}
_configItems.Clear();
_configItems = null;
_configFile = "";
}
}
}