using System; using System.Diagnostics; using System.Collections.Specialized; using System.Xml; namespace toolbag { public class Configuration { public const string CONSOLE = "Console"; public const string SERVICE = "Service"; public const string WEBSITE = "Website"; public const string PROJECT_TYPE = "ProjectType"; public const string PROJECT_NAME = "ProjectName"; public const string LOG_CONSOLE = "LogConsole"; public const string LOG_FILE = "LogFile"; public const string LOG_EVENT = "LogEvent"; private NameValueCollection settings = new NameValueCollection(); private static Configuration instance = null; private string filename = "config.xml"; private bool autosave = false; public bool Autosave { get { return autosave; } set { autosave = value; } } private Configuration() { settings[PROJECT_TYPE] = CONSOLE; settings[PROJECT_NAME] = "Project"; ReadSettings(); } public Configuration(string filename) { this.filename = filename; ReadSettings(); } private void ReadSettings() { try { XmlTextReader reader = new XmlTextReader(filename); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { string key = reader.GetAttribute("key"); if (key != null) { string value = reader.GetAttribute("value"); settings[key] = value; } } } reader.Close(); } catch (Exception ex) { Debug.Write(ex.Message); } } private void WriteSettings() { try { XmlDocument document = new XmlDocument(); XmlNode declaration = (XmlNode)document.CreateXmlDeclaration("1.0", null, null); document.AppendChild(declaration); XmlNode settingsNode = document.CreateElement("settings"); document.AppendChild(settingsNode); foreach (string key in settings.Keys) { XmlNode settingNode = document.CreateElement("setting"); XmlAttribute keyAttribute = document.CreateAttribute("key"); keyAttribute.Value = key; settingNode.Attributes.Append(keyAttribute); XmlAttribute valueAttribute = document.CreateAttribute("value"); valueAttribute.Value = settings[key]; settingNode.Attributes.Append(valueAttribute); settingsNode.AppendChild(settingNode); } document.Save(filename); } catch (Exception ex) { Debug.Write(ex.Message); } } public void Save() { WriteSettings(); } public string this[string key] { get { return settings[key]; } set { settings[key] = value; if (autosave) Save(); } } public static Configuration GetInstance() { if (instance == null) { instance = new Configuration(); } return instance; } public int GetInt32(string key) { return Int32.Parse(settings[key]); } } }