最近我做的一些项目,经常需要用到对应用程序的配置文件操作,如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=,
WebConfig=
} /// <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;
}
}

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

  1. 两种读写配置文件的方案(app.config与web.config通用)

    第一种方法:采用MS现有的ConfigurationManager来进行读写 using System.Configuration; namespace Zwj.TEMS.Common { publi ...

  2. 适用于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通用)>,现在重新整理一 ...

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

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

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

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

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

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

  6. 在Asp.Net MVC 中如何用JS访问Web.Config中appSettings的值

    应用场景: 很多时候我们要在Web.Config中添加appSettings的键值对来标识一些全局的信息,比如:调用service的domain,跳转其他网站页面的url 等等: 那么此时就涉及到了一 ...

  7. asp.net中bin目录下的 dll.refresh文件

    首先找到了这篇文章http://www.cnblogs.com/haokaibo/archive/2010/07/31/1789342.html 然后找到一篇英文的文章http://monsur.xa ...

  8. .Net 对App.config和Web.config的访问操作(增、删、读、改)

    一.首先引用Configuration 1)App.config如下: using System.Configuration;//若果还没有Configuration,右键引用文件夹添加引用,在.NE ...

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

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

随机推荐

  1. PHP使用empty检查函数返回结果时报Fatal error: Can't use function return value in write context的问题

    PHP开发时,当你使用empty检查一个函数返回的结果时会报错:Fatal error: Can't use function return value in write context 例如: &l ...

  2. 分享8款最新HTML5/CSS3功能插件及源码下载

    1.HTML5/CSS3鬼脸表情下拉菜单 超级可爱 这款HTML5/CSS3鬼脸表情下拉菜单真的很特别,虽然菜单的实现并没有利用复杂的HTML5/CSS3技术,但是创意的确不错. 在线演示 源码下载 ...

  3. [大牛翻译系列]Hadoop(3)MapReduce 连接:半连接(Semi-join)

    4.1.3 半连接(Semi-join) 假设一个场景,需要连接两个很大的数据集,例如,用户日志和OLTP的用户数据.任何一个数据集都不是足够小到可以缓存在map作业的内存中.这样看来,似乎就不能使用 ...

  4. 加载页面遮挡耗时操作任务页面--第三方开源--AndroidProgressLayout

    在Android的开发中,往往有这种需求,比如一个耗时的操作,联网获取网络图片.内容,数据库耗时读写等等,在此耗时操作过程中,开发者也许不希望用户再进行其他操作(其他操作可能会引起逻辑混乱),而此时需 ...

  5. delphi的UTF8相关函数

    delphi的UTF8相关函数 AnsiToUtf8 function Converts a string encoded in Ansi to UTF-8. PUCS4Chars function ...

  6. Java对象校验框架之Oval

      只要有接口,就会有参数的校验,目前开源的校验框架已经非常多了,不过不得不提一下Oval.OVal 是一个可扩展的Java对象数据验证框架,验证的规则可以通过配置文件.Annotation.POJO ...

  7. (转)Android Support Percent百分比布局

    一.概述 周末游戏打得过猛,于是周天熬夜码代码,周一早上浑浑噩噩的发现 android-percent-support-lib-sample(https://github.com/JulienGeno ...

  8. Microsoft server software support for Microsoft Azure virtual machines

    http://support.microsoft.com/kb/2721672/en-us  Article ID: 2721672 - Last Review: November 22, 2014 ...

  9. Linux nmon 监控工具使用

    Linux 系统下监控指标及指标查看 一.工具介绍     Linux 系统下资源监控使用nmon 工具.它可以帮助在一个屏幕上显示所有重要的性能优化信息,并动态地对其进行更新且并不会消耗大量的CPU ...

  10. React和Backbone优缺点

    1.React 使用了VDOM,方便移植至其他平台,如Android等:Backbone更灵活,且与Jquery结合比较好. 2.React如果不与Jsx结合易读性很差;Backbone有强大的模板功 ...