I have created a simple ConfigManager
in C# that loads each line of a file. If the line contains =
then it gets the before =
(the key) and the after =
(the value).
For example, my config file would look something like this:
# Comment here
MyConfigKey1=MyValue1
MyConfigKey2=MyValue2
MyConfigKey3=MyValue3
Obviously my config file wouldn't be that, but that's the layout of it. If the file is unreadable or is not found then the defaults are used.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace Sirius.Core.Config
{
internal sealed class ConfigManager
{
private readonly Dictionary<string, string> _configItems;
public ConfigManager(string configFile)
{
_configItems = new Dictionary<string, string>();
var logManager = Sirius.GetServer().GetLogManager();
var stopwatch = Stopwatch.StartNew();
try
{
if (File.Exists(configFile) && Sirius.GetServer().GetUtility().IsFileLocked(new FileInfo(configFile)))
{
_configItems = File.ReadLines(configFile)
.Where(IsConfigurationLine)
.Select(line => line.Split('='))
.ToDictionary(line => line[0], line => line[1]);
}
else
{
_configItems.Add("database.host", "localhost");
_configItems.Add("database.username", "root");
_configItems.Add("database.password", "");
_configItems.Add("database.name", "database");
_configItems.Add("database.port", "3306");
_configItems.Add("database.max_connections", "10000");
_configItems.Add("sockets.port", "30000");
_configItems.Add("sockets.backlog", "50");
logManager.Warn("Using the default configuration.");
}
}
catch (Exception exception)
{
logManager.Error(exception.Message, exception);
}
finally
{
logManager.Information("Loaded Config Data [" + stopwatch.ElapsedMilliseconds + "ms]");
stopwatch.Stop();
}
}
private static bool IsConfigurationLine(string line)
{
return !line.StartsWith("#") && line.Contains("=");
}
public string GetConfigElement(string key)
{
string value;
if (!_configItems.TryGetValue(key, out value))
{
Sirius.GetServer().GetLogManager().Error("Missing configuration key `" + key + "`");
}
return value;
}
}
}