using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Xml;
using System.Reflection;
namespace Walter.K.Wang.Config
...{
/**//// <summary>
/// 讀寫配置文件操作類
/// </summary>
public class Config
...{
/**//// <summary>
/// 讀配置文件
/// </summary>
/// <param name="key">關鍵字</param>
/// <returns>直</returns>
public string ReadConfig(string key)
...{
return ConfigurationManager.AppSettings[key].ToString();
}

/**//// <summary>
/// 寫配置文件
/// </summary>
/// <param name="key">關鍵字</param>
/// <param name="value">直</param>
public void WriteConfig(string key,string value)
...{
XmlDocument doc = new XmlDocument();
//創建DLL文件
doc.Load(Assembly.GetEntryAssembly().Location + ".config");
//程序中片段碼
XmlNode node = doc.SelectSingleNode("//appSettings");
if (node == null)
throw new InvalidOperationException("沒有找到AppSettings接點.");
try
...{
XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));
if (elem != null)
...{
elem.SetAttribute("value", value);
}
else
...{
elem = doc.CreateElement("add");
elem.SetAttribute("key", key);
elem.SetAttribute("value", value);
node.AppendChild(elem);
}
doc.Save(Assembly.GetEntryAssembly().Location + ".config");
}
catch(Exception Err)
...{
throw new Exception(Err.Message);
}
}
}
}
本文介绍了一个用于读取和修改应用程序配置文件的实用类。该类提供了读取配置项及更新配置值的功能,并通过XML操作实现了对.config文件的直接编辑。
5087

被折叠的 条评论
为什么被折叠?



