Environment
* Visual Studio 2013
XML Property File
* Add a new XML property file in the Properties directory:
<?xml version="1.0" encoding="utf-8"?> <Settings> <add key="prop1" value="value1" /> <add key="prop2" value="value2" /> </Settings>
MyProperties Class
public class MyProperties { private static readonly ILog log = LogManager.GetLogger(typeof(MyProperties)); private const string propDir = "Properties"; private const string myprofile = propDir + "/fcx.xml"; private Dictionary<string, string> myprops = null; // Singleton private static MyProperties instance; private MyProperties() { } public static MyProperties Instance { get { if (instance == null) { instance = new MyProperties(); instance.LoadProperties(); } return instance; } } // Find value from key public string FindValue(string key) { return this.FindValue(key, this.myprops); } // =================================================== Common private string FindValue(string key, Dictionary<string, string> props) { foreach (string k in props.Keys) { if (key.Equals(k, StringComparison.InvariantCultureIgnoreCase)) { return props[key]; } } return null; } private void LoadProperties() { // Load once if (myprops == null) { myprops = new Dictionary<string, string>(); this.LoadProperties(myprofile, myprops); } } private void LoadProperties(string file, Dictionary<string, string> props) { if (!File.Exists(file)) { log.ErrorFormat("Property file not found: {0}", myprofile); Environment.Exit(0); } XmlDocument doc = new XmlDocument(); doc.Load(file); foreach (XmlNode c in doc.ChildNodes) { if (c.Name.Equals("Settings")) { foreach (XmlNode n in c.ChildNodes) { if (n.Name.Equals("add", StringComparison.InvariantCultureIgnoreCase)) { props.Add( n.Attributes["key"].Value, n.Attributes["value"].Value); } } } } } }
Unit Test
[TestClass] public class UnitTest1 { private static readonly ILog log = LogManager.GetLogger(typeof(UnitTest1)); [TestMethod] public void TestMethod1() { string k = "prop1"; string v = MyProperties.Instance.FindValue(k); log.InfoFormat("Found value {0} for key {1}.", v, k); } }