第一种方法:采用MS现有的ConfigurationManager来进行读写

using System.Configuration;

namespace Zwj.TEMS.Common
{
public abstract class ConfigHelper
{
private ConfigHelper()
{ } /// <summary>
/// 获取配置值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static string GetAppSettingValue(string key)
{
return ConfigurationManager.AppSettings[key];
} /// <summary>
/// 设置配置值(存在则更新,不存在则新增)
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public static void SetAppSettingValue(string key, string value)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var setting = config.AppSettings.Settings[key];
if (setting==null)
{
config.AppSettings.Settings.Add(key, value);
}
else
{
setting.Value = value;
} config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
} /// <summary>
/// 删除配置值
/// </summary>
/// <param name="key"></param>
public static void RemoveAppSetting(string key)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove(key);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
} /// <summary>
/// 获取连接字符串
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string GetConnectionString(string name)
{
return ConfigurationManager.ConnectionStrings[name].ConnectionString;
} /// <summary>
/// 设置连接字符串的值(存在则更新,不存在则新增)
/// </summary>
/// <param name="name"></param>
/// <param name="connstr"></param>
/// <param name="provider"></param>
public static void SetConnectionString(string name,string connstr, string provider)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringSettings connStrSettings = config.ConnectionStrings.ConnectionStrings[name];
if (connStrSettings != null)
{
connStrSettings.ConnectionString = connstr;
connStrSettings.ProviderName = provider;
}
else
{
connStrSettings = new ConnectionStringSettings(name, connstr, provider);
config.ConnectionStrings.ConnectionStrings.Add(connStrSettings);
} config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
} /// <summary>
/// 删除连接字符串配置项
/// </summary>
/// <param name="name"></param>
public static void RemoveConnectionString(string name)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings.Remove(name);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
} }
}

 注意:不能直接使用ConfigurationManager.AppSettings及ConfigurationManager.ConnectionStrings进行写操作(即:Add,Remove),因为这两个属性是只读的,本人之前也疑惑,明明能够调用Add,Remove方法,但使用时却报错。

第二种方法:采用原生的XML+XPATH来读写(来源于网络)

//==============================================
// FileName: ConfigManager
// Description: 静态方法业务类,用于对C#、ASP.NET中的WinForm & WebForm 项目程序配置文件
// app.config和web.config的[appSettings]和[connectionStrings]节点进行新增、修改、删除和读取相关的操作。
//==============================================
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Collections.Generic;
using System.Text;
using System.Xml; public enum ConfigurationFile
{
AppConfig = 1,
WebConfig = 2
}
/// <summary>
/// ConfigManager 应用程序配置文件管理器
/// </summary>
public class ConfigManager
{
public ConfigManager()
{
//
// TODO: 在此处添加构造函数逻辑
//
} /// <summary>
/// 对[appSettings]节点依据Key值读取到Value值,返回字符串
/// </summary>
/// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
/// <param name="key">要读取的Key值</param>
/// <returns>返回Value值的字符串</returns>
public static string ReadValueByKey(ConfigurationFile configurationFile, string key)
{
string value = string.Empty;
string filename = string.Empty;
if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
{
filename = System.Windows.Forms.Application.ExecutablePath + ".config";
}
else
{
filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
} XmlDocument doc = new XmlDocument();
doc.Load(filename); //加载配置文件
XmlNode node = doc.SelectSingleNode("//appSettings"); //得到[appSettings]节点
////得到[appSettings]节点中关于Key的子节点
XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
if (element != null)
{
value = element.GetAttribute("value");
}
return value;
}
/// <summary>
/// 对[connectionStrings]节点依据name值读取到connectionString值,返回字符串
/// </summary>
/// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
/// <param name="name">要读取的name值</param>
/// <returns>返回connectionString值的字符串</returns>
public static string ReadConnectionStringByName(ConfigurationFile configurationFile, string name)
{
string connectionString = string.Empty;
string filename = string.Empty;
if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
{
filename = System.Windows.Forms.Application.ExecutablePath + ".config";
}
else
{
filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
}
XmlDocument doc = new XmlDocument();
doc.Load(filename); //加载配置文件
XmlNode node = doc.SelectSingleNode("//connectionStrings"); //得到[appSettings]节点
////得到[connectionString]节点中关于name的子节点
XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name='" + name + "']");
if (element != null)
{
connectionString = element.GetAttribute("connectionString");
}
return connectionString;
}
/// <summary>
/// 更新或新增[appSettings]节点的子节点值,存在则更新子节点Value,不存在则新增子节点,返回成功与否布尔值
/// </summary>
/// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
/// <param name="key">子节点Key值</param>
/// <param name="value">子节点value值</param>
/// <returns>返回成功与否布尔值</returns>
public static bool UpdateOrCreateAppSetting(ConfigurationFile configurationFile, string key, string value)
{
bool isSuccess = false;
string filename = string.Empty;
if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
{
filename = System.Windows.Forms.Application.ExecutablePath + ".config";
}
else
{
filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
}
XmlDocument doc = new XmlDocument();
doc.Load(filename); //加载配置文件
XmlNode node = doc.SelectSingleNode("//appSettings"); //得到[appSettings]节点
try
{
////得到[appSettings]节点中关于Key的子节点
XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
if (element != null)
{
//存在则更新子节点Value
element.SetAttribute("value", value);
}
else
{
//不存在则新增子节点
XmlElement subElement = doc.CreateElement("add");
subElement.SetAttribute("key", key);
subElement.SetAttribute("value", value);
node.AppendChild(subElement);
}
//保存至配置文件(方式一)
using (XmlTextWriter xmlwriter = new XmlTextWriter(filename, null))
{
xmlwriter.Formatting = Formatting.Indented;
doc.WriteTo(xmlwriter);
xmlwriter.Flush();
}
isSuccess = true;
}
catch (Exception ex)
{
isSuccess = false;
throw ex;
}
return isSuccess;
}
/// <summary>
/// 更新或新增[connectionStrings]节点的子节点值,存在则更新子节点,不存在则新增子节点,返回成功与否布尔值
/// </summary>
/// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
/// <param name="name">子节点name值</param>
/// <param name="connectionString">子节点connectionString值</param>
/// <param name="providerName">子节点providerName值</param>
/// <returns>返回成功与否布尔值</returns>
public static bool UpdateOrCreateConnectionString(ConfigurationFile configurationFile, string name, string connectionString, string providerName)
{
bool isSuccess = false;
string filename = string.Empty;
if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
{
filename = System.Windows.Forms.Application.ExecutablePath + ".config";
}
else
{
filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
}
XmlDocument doc = new XmlDocument();
doc.Load(filename); //加载配置文件
XmlNode node = doc.SelectSingleNode("//connectionStrings"); //得到[connectionStrings]节点
try
{
////得到[connectionStrings]节点中关于Name的子节点
XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name='" + name + "']");
if (element != null)
{
//存在则更新子节点
element.SetAttribute("connectionString", connectionString);
element.SetAttribute("providerName", providerName);
}
else
{
//不存在则新增子节点
XmlElement subElement = doc.CreateElement("add");
subElement.SetAttribute("name", name);
subElement.SetAttribute("connectionString", connectionString);
subElement.SetAttribute("providerName", providerName);
node.AppendChild(subElement);
}
//保存至配置文件(方式二)
doc.Save(filename);
isSuccess = true;
}
catch (Exception ex)
{
isSuccess = false;
throw ex;
}
return isSuccess;
}
/// <summary>
/// 删除[appSettings]节点中包含Key值的子节点,返回成功与否布尔值
/// </summary>
/// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
/// <param name="key">要删除的子节点Key值</param>
/// <returns>返回成功与否布尔值</returns>
public static bool DeleteByKey(ConfigurationFile configurationFile, string key)
{
bool isSuccess = false;
string filename = string.Empty;
if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
{
filename = System.Windows.Forms.Application.ExecutablePath + ".config";
}
else
{
filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
}
XmlDocument doc = new XmlDocument();
doc.Load(filename); //加载配置文件
XmlNode node = doc.SelectSingleNode("//appSettings"); //得到[appSettings]节点
////得到[appSettings]节点中关于Key的子节点
XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
if (element != null)
{
//存在则删除子节点
element.ParentNode.RemoveChild(element);
}
else
{
//不存在
}
try
{
//保存至配置文件(方式一)
using (XmlTextWriter xmlwriter = new XmlTextWriter(filename, null))
{
xmlwriter.Formatting = Formatting.Indented;
doc.WriteTo(xmlwriter);
xmlwriter.Flush();
}
isSuccess = true;
}
catch (Exception ex)
{
isSuccess = false;
}
return isSuccess;
}
/// <summary>
/// 删除[connectionStrings]节点中包含name值的子节点,返回成功与否布尔值
/// </summary>
/// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
/// <param name="name">要删除的子节点name值</param>
/// <returns>返回成功与否布尔值</returns>
public static bool DeleteByName(ConfigurationFile configurationFile, string name)
{
bool isSuccess = false;
string filename = string.Empty;
if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
{
filename = System.Windows.Forms.Application.ExecutablePath + ".config";
}
else
{
filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
}
XmlDocument doc = new XmlDocument();
doc.Load(filename); //加载配置文件
XmlNode node = doc.SelectSingleNode("//connectionStrings"); //得到[connectionStrings]节点
////得到[connectionStrings]节点中关于Name的子节点
XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name='" + name + "']");
if (element != null)
{
//存在则删除子节点
node.RemoveChild(element);
}
else
{
//不存在
}
try
{
//保存至配置文件(方式二)
doc.Save(filename);
isSuccess = true;
}
catch (Exception ex)
{
isSuccess = false;
}
return isSuccess;
}
}

更多IT相关技术文章与资讯,欢迎光临我的个人网站:http://www.zuowenjun.cn

两种读写配置文件的方案(app.config与web.config通用)的更多相关文章

  1. 适用于app.config与web.config的ConfigUtil读写工具类 基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类) 基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

    适用于app.config与web.config的ConfigUtil读写工具类   之前文章:<两种读写配置文件的方案(app.config与web.config通用)>,现在重新整理一 ...

  2. 适用于app.config与web.config的ConfigUtil读写工具类

    之前文章:<两种读写配置文件的方案(app.config与web.config通用)>,现在重新整理一个更完善的版本,增加批量读写以及指定配置文件路径,代码如下: using System ...

  3. App.config和Web.config配置文件的自定义配置节点

    前言 昨天修改代码发现了一个问题,由于自己要在WCF服务接口中添加了一个方法,那么在相应调用的地方进行更新服务就可以了,不料意外发生了,竟然无法更新.左查右查终于发现了问题.App.config配置文 ...

  4. 配置文件(Machine.config、Web.config、App.config)

    Machine.config1.该文件在Windows目录下\Microsoft.net\framework\[version]\Config\2.为了提高性能,该文件只包含不同于默认值的设置.并且定 ...

  5. C# 应用程序配置文件App.Config和web.config

    应用程序配置文件,对于asp.net是 web.config,对于WINFORM程序是 App.Config(ExeName.exe.config). 配置文件,对于程序本身来说,就是基础和依据,其本 ...

  6. 关于C#和ASP.NET中对App.config和Web.config文件里的[appSettings]和[connectionStrings]节点进行新增、修改、删除和读取相关的操作

    最近我做的一些项目,经常需要用到对应用程序的配置文件操作,如app.config和web.config的配置文件,特别是对配置文件中的[appSettings]和[connectionStrings] ...

  7. Visual Studio中xml文件使用app.config、web.config等的智能提示的方法

    在.Net开发的过程中,有时我们需要使用Xml文件作为配置文件(基于某些情况的考虑),而不是app.config.web.config这种,但是我们在xml中配置时希望可以增加类似编辑app.conf ...

  8. 描述 Machine.Config 和 Web.Config(转载)

    NET Framework 提供的配置管理包括范围广泛的设置,允许管理员管理 Web 应用程序及其环境.这些设置存储在 XML 配置文件中,其中一些控制计算机范围的设置,另一些控制应用程序特定的配置. ...

  9. App.config和Web.config配置文件的配置节点的解析

    前言 在http://www.cnblogs.com/aehyok/p/3558661.html这篇博文中,大致对配置文件有了初步的了解,并且在文中有提到过<appSettings>和&l ...

随机推荐

  1. Intellij IDEA工具Java web 环境搭建

    Java web 环境搭建 环境依赖 操作系统:Windows 7 64位 开发工具:IntelliJ IDEA 13.1.4 开发工具依赖环境 JDK版本:1.7+ 开发工具依赖插件 包管理:Mav ...

  2. node(websocket)

    websocket原本是html5下实现长链接的一个特性,当前已被众多浏览器支持. 在websocket协议中,首先通过http交换一次握手,明确将协议升级至websocket.同时建立一个TCP通道 ...

  3. UWP滑动后退

    经过近些年智能手机App的不断发展,用户已经不仅仅满足于功能上的需求.UI.设计等非功能点逐渐在App体验中占了大多数的分数.不知从何时起,滑动手势就成为了App的一个标配.他不仅仅是一个功能,更是一 ...

  4. Java虚拟机9:Java类加载机制

    前言 我们知道我们写的程序经过编译后成为了.class文件,.class文件中描述了类的各种信息,最终都需要加载到虚拟机之后才能运行和使用.而虚拟机如何加载这些.class文件?.class文件的信息 ...

  5. 打通移动App开发的任督二脉、实现移动互联创业的中国梦

    年初的两会上,第一次听到克强总理讲到“互联网+”的计划,当时就让我为之感到无比振奋.我个人的理解是:“互联网+”的本质就是要对传统行业供需双方的重构,通过移动互联技术来推动各个行业上的全民创新,促使中 ...

  6. ThoughtWorks持续集成平台GO开源了

    ThoughtWorks 持续集成平台Go最近宣布开源了.其基于Apache 2.0 开源协议. Go下载地址为http://www.go.cd/download/. 下面是几张来自官方的视图: GO ...

  7. Bootstrap~大叔封装的弹层

    回到目录 对于Bootstrap的弹层,插件有很多,今天主要用的是它自带的功能,通过bootstrap提供的模式窗口来实现的,而大叔主要对使用方法进行了封装,开发人员可以自己动态传入弹层的HTML内容 ...

  8. 爱上MVC3~布局页的继承与扩展

    回到 目录 在MVC3中引入了Razor引擎,这对于代码的表现力上是个突破,同时母板页也变成了_Layout,所以,我们就习惯上称它为布局页面,在razor里,布局页面是可以继承的,即,一个上下公用的 ...

  9. IOS笔记045-UIDatePicker和UIPickerView

    这是两种可以上下滚动的控件. 这是UIDatePicker,可以显示日期和时间. 这个是UIPickerView,显示类似几个选择项的界面. 注意点:PickerView的高度不能改,默认162,Pi ...

  10. token防止表单重复提交

    出现表单重复提交的三种情况: 一.服务器响应缓慢,用户多次点击提交按钮. 二.提交成功后刷新页面. 三.提交成功后返回表单页面再次点击提交. package com.jalja.token; impo ...