当前位置:文档之家› C#读写配置文件

C#读写配置文件

Windows 应用程序:
///<summary>
///发布后就可以读取了
///</summary>
private readonly string strFileName = AppDomain.CurrentDomain.BaseDirectory + "Windows_RWConfig.exe.config"; //获得配置文件的全路径
///<summary>
///修改配置文件
///</summary>
///<param name="key">key</param>
///<param name="value">value</param>
private void UpdateConfig(string key, string value)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(strFileName);
//找出名称为“add”的所有元素
XmlNodeList nodes = xDoc.GetElementsByTagName("add");
for (int i = 0; i < nodes.Count; i++)
{
//获得元素的key属性
XmlAttribute att = nodes[i].Attributes["key"];
//根据元素的第一个属性来判断元素是不是目标元素
if (att.Value == key)
{
//对目标元素中的第二个属性赋值
att = nodes[i].Attributes["value"];
att.Value = value;
break;
}
}
//保存上面的修改
xDoc.Save(strFileName);
}
///<summary>
///读取配置文件
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
private void btnR_Click(object sender, EventArgs e)
{
lblContent.Text = ConfigurationManager.AppSettings["ConnectionString"];
}
///<summary>
///添加配置文件
///</summary>
///<param name="key">key</param>
///<param name="value">value</param>
private void AddConfig(string key, string value)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(strFileName);
XmlNode xNode = xDoc.SelectSingleNode("//appSettings");
XmlElement xElem1 = xDoc.CreateElement("add");
xElem1.SetAttribute("key", key);
xElem1.SetAttribute("value", value);
xNode.AppendChild(xElem1);
//保存上面的修改
xDoc.Save(strFileName);
}
Web 应用程序:
private readonly Configuration config =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(System.Web.HttpContext .Current.Request.ApplicationPath);
protected void WriteConfig(string key, string value)
{
AppSettingsSection appSection = (AppSettingsSection)
config.GetSection("appSettings");
if (appSection.Settings[key] != null)
{
appSection.Settings.Remove(key);
}
appSection.Settings.Add(key, value); config.Save();
}。

相关主题