您的位置:首页 > 编程语言 > C#

C#操作配置文件

2012-11-13 14:14 369 查看
读取指定节点的值:

///<summary>
///返回*.config文件中appSettings配置节的value项
///</summary>
///<param name="strKey"></param>
///<returns></returns>
public static string GetAppConfig(string strKey)
{
foreach (string key in ConfigurationManager.AppSettings)
{
if (key == strKey)
{
return ConfigurationManager.AppSettings[strKey];
}
}
return null;
}


修改以及增加一个节点(Key),修改其实就是判断该Key是否存在,存在则删除,再创建。

///<summary>
///在*.config文件中appSettings配置节增加一对键、值对
///</summary>
///<param name="newKey"></param>
///<param name="newValue"></param>
public static void UpdateAppConfig(string newKey, string newValue)
{
bool isModified = false;
foreach (string key in ConfigurationManager.AppSettings)
{
if (key == newKey)
{
isModified = true;
}
}

Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// 如果操作的Key 已存在,则删除
if (isModified)
{
config.AppSettings.Settings.Remove(newKey);
}
// 在配置文件中添加节点
config.AppSettings.Settings.Add(newKey, newValue);
// 修改配置文件后还需要保存
config.Save(ConfigurationSaveMode.Modified);
// 重置配置文件,如果不执行这行语句,已更新的配置文件不会得到应用
ConfigurationManager.RefreshSection("appSettings");
}


读写配置文件很简单,也很方便。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: