NooM,
The configuration manager should be a simple class that allows you to store at least key-value pairs in a consistent way across the application.
I wrote something myself which I believe would be useful:
using System;using System.Collections;using System.IO;namespace Utils{ public class ConfigManager : IDisposable { private bool _disposed; private StringDictionary _dataset; private string _configFilename; private readonly char _splitter = '='; public ConfigManager(string configFilename) { _dataset = new StringDictionary(); _configFilename = configFilename; Reload(); } public void Save() { using (var file = new StreamWriter(_configFilename, false)) { foreach (DictionaryEntry dataElement in _dataset) { var line = (string)dataElement.Key + _splitter + (string)dataElement.Value; file.WriteLine(line); } file.Close(); } } public void Reload() { if (!File.Exists(_configFilename)) return; _dataset.Clear(); using (var file = new StreamReader(_configFilename)) { if (file.BaseStream.Length > 0) { do { var str = file.ReadLine(); var idx = str.IndexOf(_splitter); if (idx >= 0) { var key = prepareKey(str.Substring(0, idx)); var value = str.Substring(idx + 1, str.Length - (idx + 1)); _dataset.Add(key, value); } } while (!file.EndOfStream); } file.Close(); } } public void SetValue (string key, string value) { key = prepareKey(key); if (_dataset.ContainsKey(key)) { _dataset[key] = value.Trim(); } else { _dataset.Add(key, value.Trim()); } } public string GetValue (string key) { return _dataset[prepareKey(key)]; } private string prepareKey (string key) { return key.Trim().ToLower(); } #region Implementation of IDisposable /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <filterpriority>2</filterpriority> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose (bool disposing) { if (!_disposed) { if (disposing) { _dataset.Clear(); } } _disposed = true; } ~ConfigManager() { Dispose(false); } #endregion }}
An example of how to use it:
using (var cm = new ConfigManager(@"SDconfconfig.txt")) { cm.SetValue("key", "value"); // some setting example cm.SetValue("Address", "http://127.0.0.1"); // some setting example cm.Save(); } using (var cm = new ConfigManager(@"SDconfconfig.txt")) { Debug.Print("Address: " + cm.GetValue("Address")); }
- NooM likes this