/// <summary> ///简单配置文件,只包含字符串键值信息 /// </summary> public class SimpleConfigFile { /// <summary> /// 静态构造函数 /// </summary> static SimpleConfigFile() { const string fileName = "appconfig.xml"; var fullPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase), fileName);//获取运行程序的当前路径 Default=File.Exists(fullPath)?new SimpleConfigFile(fullPath) : new SimpleConfigFile(); } /// <summary> /// 单例 /// </summary> public static SimpleConfigFile Default; public IDictionary<string, string> AppSettings { get; private set; } private readonly string _configFile; /// <summary> /// 构造函数 /// </summary> internal SimpleConfigFile() { AppSettings=new Dictionary<string, string>(); } /// <summary> /// 构造函数重载 /// </summary> /// <param name="configFile"></param> internal SimpleConfigFile(string configFile) { _configFile = configFile; ReloadAppSettings(_configFile); } /// <summary> /// 重新加载appconfig.xml的内容 /// </summary> public void Reload() { if (_configFile!=null) { ReloadAppSettings(_configFile); } } /// <summary> /// 读取appconfig.xml的内容,其实就是xml文件的读操作 /// </summary> /// <param name="configFile"></param> private void ReloadAppSettings(string configFile) { AppSettings=new Dictionary<string, string>(); var xmlDoc = new XmlDocument(); xmlDoc.Load(configFile); var nodes = xmlDoc.GetElementsByTagName("appSettings"); if (nodes.Count > 0) { var outerNode = nodes[0]; foreach (XmlNode node in outerNode.ChildNodes) { AppSettings[node.Name] = node.InnerText; } } } }我们在窗体上放了一个listbox,formload里面调用appconfig.xml读取的操作: 具体代码如下:
private void Form1_Load(object sender, EventArgs e) { var dic = SimpleConfigFile.Default.AppSettings; foreach (var key in dic.Keys) { listBox1.Items.Add(key + ":" + dic[key]); } }
我们appconfig.xml的真实内容如下:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <Address>192.168.1.1</Address> <Stock>BJ</Stock> </appSettings> </configuration>运行结果如下图: