vs2003下的web.config操作方法

using System;
using System.Xml;
using System.Configuration;
namespace EmanUtils
{
/** <summary>
/// 读配置文件的操作 
/// Config操作类
/// </summary>
public class ConfigHelper
{
public ConfigHelper()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
#region GetConfigValueOfKey(string Key) 得到配置文件的值
public string GetConfigValueOfKey(string Key)
{
try
{
string value = ConfigurationSettings.AppSettings[Key];
//Console.WriteLine(Key);
//Console.WriteLine(value);
return value;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
return "";
}
}
#endregion
// #region abstract CreateConfigValueOfKey 需要开发
// public void CreateConfigValueOfKey(string Key , string KeyValue)
// {
// 
// }
// #endregion
#region UpdateConfigValueOfKey
public void UpdateConfigValueOfKey(string Key , string KeyValue)
{
XmlDocument doc=new XmlDocument();
//获得配置文件的全路径
string strFileName=AppDomain.CurrentDomain.BaseDirectory.ToString()+"App.config";
Console.WriteLine(strFileName);
//return;
doc.Load(strFileName);
//找出名称为“add”的所有元素

//bool IsExist = false;
XmlNodeList nodes=doc.GetElementsByTagName("add");
for(int i=0;i<nodes.Count;i++)
{
//获得将当前元素的key属性
XmlAttribute att=nodes[i].Attributes["key"];
//根据元素的第一个属性来判断当前的元素是不是目标元素
if (att.Value.ToString().Equals(Key)) 
{
//对目标元素中的第二个属性赋值
att=nodes[i].Attributes["value"];
att.Value=KeyValue;
//IsExist = true;
break;
}
}
//保存上面的修改
doc.Save(strFileName);
} 
#endregion
}
}
/// <summary>
/// 修改指定配置节节点信息的值
/// 作 者: KidYang
/// 日 期: 2007-03-27
/// </summary>
/// <param name="appSettingsName">给定配置节节点</param>
/// <param name="newValue">目标值</param>
public static void WriteWebConfig(string appSettingsName, string newValue)
{
string fileName = HttpContext.Current.Server.MapPath(@"~\Web.config");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(fileName);
XmlNodeList topM = xmlDoc.DocumentElement.ChildNodes;
foreach (XmlElement element in topM)
{
#region 取得目标节点,并赋新值

if (element.Name == "appSettings")
{
XmlNodeList node = element.ChildNodes;
if (node.Count > 0)
{
foreach (XmlElement el in node)
{
if (el.Attributes["key"].Value == appSettingsName)
{
el.Attributes["value"].Value = newValue;
xmlDoc.Save(fileName);
return;
}
}
}
}

#endregion
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值