在实际的项目开发中,对于项目的相关信息的配置较多,在.NET项目中,我们较多的将程序的相关配置直接存储的.config文件中,例如web.config和app.config。

.NET中配置文件分为两部分:配置的实际内容(位于appSetting节点);指定了节点的处理程序(位于configSections节点)。

在.NET程序中,.config文件存储相关配置是以xml格式,如果我们需要对配置文件进行读取和写入,以及相关节点的删除,我们可以直接采用处理xml文件的方式进行操作。也可以采用.NET提供的类System.Configuration进行相关操作。

在System.Configuration类型中,对外提供了几种方法调用,在这里介绍三种较为常用的:AppSettings,ConnectionStrings,GetSection。

接下来看一下这些方法:

1.AppSettings属性:

   /// <summary>
/// 获取当前应用程序默认配置的 <see cref="T:System.Configuration.AppSettingsSection"/> 数据。
/// </summary>
///
/// <returns>
/// 返回一个 <see cref="T:System.Collections.Specialized.NameValueCollection"/> 对象,该对象包含当前应用程序默认配置的 <see cref="T:System.Configuration.AppSettingsSection"/> 对象的内容。
/// </returns>
/// <exception cref="T:System.Configuration.ConfigurationErrorsException">未能使用应用程序设置数据检索 <see cref="T:System.Collections.Specialized.NameValueCollection"/> 对象。</exception>
public static NameValueCollection AppSettings { get; }

2.ConnectionStrings属性:

    /// <summary>
/// 获取当前应用程序默认配置的 <see cref="T:System.Configuration.ConnectionStringsSection"/> 数据。
/// </summary>
///
/// <returns>
/// 返回一个 <see cref="T:System.Configuration.ConnectionStringSettingsCollection"/> 对象,该对象包含当前应用程序默认配置的 <see cref="T:System.Configuration.ConnectionStringsSection"/> 对象的内容。
/// </returns>
/// <exception cref="T:System.Configuration.ConfigurationErrorsException">未能检索 <see cref="T:System.Configuration.ConnectionStringSettingsCollection"/> 对象。</exception>
public static ConnectionStringSettingsCollection ConnectionStrings { get; }

3.GetSection方法:

    /// <summary>
/// 检索当前应用程序默认配置的指定配置节。
/// </summary>
///
/// <returns>
/// 指定的 <see cref="T:System.Configuration.ConfigurationSection"/> 对象,或者,如果该节不存在,则为 null。
/// </returns>
/// <param name="sectionName">配置节的路径和名称。</param><exception cref="T:System.Configuration.ConfigurationErrorsException">未能加载配置文件。</exception>
public static object GetSection(string sectionName);

以上对几种方法进行了说明,接下来我们具体看一下在项目中对配置文件的操作:

1.获取配置值:

        /// <summary>
/// 获取配置值
/// </summary>
/// <param name="key">节点名称</param>
/// <returns></returns>
public static string GetAppSettingValue(string key)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(key);
}
return ConfigurationManager.AppSettings[key];
}

2.获取连接字符串:

        /// <summary>
/// 获取连接字符串
/// </summary>
/// <param name="name">连接字符串名称</param>
/// <returns></returns>
public static string GetConnectionString(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException(name);
}
return ConfigurationManager.ConnectionStrings[name].ConnectionString;
}

3.获取节点的所有属性(处理单个节点):

        /// <summary>
/// 获取节点的所有属性(处理单个节点)
/// </summary>
/// <param name="name">节点名称</param>
/// <returns>属性的Hashtable列表</returns>
public static Hashtable GetNodeAttribute(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException(name);
}
return (Hashtable)ConfigurationManager.GetSection(name);
}

以上的是三种获取配置文件的相关节点的操作,以下提供几种全局的写入和删除操作方法:

4.设置配置值(存在则更新,不存在则新增):

        /// <summary>
/// 设置配置值(存在则更新,不存在则新增)
/// </summary>
/// <param name="key">节点名称</param>
/// <param name="value">节点值</param>
public static void SetAppSettingValue(string key, string value)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(key);
}
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException(value);
}
try
{
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");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

5.删除配置值:

         /// <summary>
/// 删除配置值
/// </summary>
/// <param name="key">节点名称</param>
public static void RemoveAppSetting(string key)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(key);
}
try
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove(key);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

6.设置连接字符串的值(存在则更新,不存在则新增):

        /// <summary>
/// 设置连接字符串的值(存在则更新,不存在则新增)
/// </summary>
/// <param name="name">名称</param>
/// <param name="connstr">连接字符串</param>
/// <param name="provider">程序名称属性</param>
public static void SetConnectionString(string name, string connstr, string provider)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException(name);
}
if (string.IsNullOrEmpty(connstr))
{
throw new ArgumentNullException(connstr);
}
if (string.IsNullOrEmpty(provider))
{
throw new ArgumentNullException(provider);
}
try
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var 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");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

7.删除连接字符串配置项:

        /// <summary>
/// 删除连接字符串配置项
/// </summary>
/// <param name="name">字符串名称</param>
public static void RemoveConnectionString(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException(name);
}
try
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings.Remove(name);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

以上的几种新增和删除操作中,如果测试过就会发现本地的.config文件中没有对应的新增节点,以及需要删除的文件节点也没有删除掉。这个原因主要是”在新增appSettings节点时,不会写入App.config或web.config中,因为AppSetting这样的节点属于内置节点,会存储在Machine.config文件中。.NET内置的处理程序定义于machine.config中,提供全局服务,无须进行任何额外工作就可以直接使用。“

如果需要对项目中的配置文件进行新增和删除操作,现在提供一种方法,采用对xml文件的操作方式:

8.更新或新增[appSettings]节点的子节点值,存在则更新子节点Value,不存在则新增子节点,返回成功与否布尔值:

        /// <summary>
/// 更新或新增[appSettings]节点的子节点值,存在则更新子节点Value,不存在则新增子节点,返回成功与否布尔值
/// </summary>
/// <param name="filename">配置文件的路径</param>
/// <param name="key">子节点Key值</param>
/// <param name="value">子节点value值</param>
/// <returns>返回成功与否布尔值</returns>
public static bool UpdateOrCreateAppSetting(string filename, string key, string value)
{
if (string.IsNullOrEmpty(filename))
{
throw new ArgumentNullException(filename);
}
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(key);
}
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException(value);
}
var doc = new XmlDocument();
//加载配置文件
doc.Load(filename);
//得到[appSettings]节点
var node = doc.SelectSingleNode("//appSettings");
try
{
//得到[appSettings]节点中关于Key的子节点
if (node != null)
{
var element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
if (element != null)
{
//存在则更新子节点Value
element.SetAttribute("value", value);
}
else
{
//不存在则新增子节点
var subElement = doc.CreateElement("add");
subElement.SetAttribute("key", key);
subElement.SetAttribute("value", value);
node.AppendChild(subElement);
}
}
//保存至配置文件(方式一)
using (var xmlwriter = new XmlTextWriter(filename, null))
{
xmlwriter.Formatting = Formatting.Indented;
doc.WriteTo(xmlwriter);
xmlwriter.Flush();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return true;
}

9.更新或新增[connectionStrings]节点的子节点值,存在则更新子节点,不存在则新增子节点,返回成功与否布尔值:

        /// <summary>
/// 更新或新增[connectionStrings]节点的子节点值,存在则更新子节点,不存在则新增子节点,返回成功与否布尔值
/// </summary>
/// <param name="filename">配置文件路径</param>
/// <param name="name">子节点name值</param>
/// <param name="connectionString">子节点connectionString值</param>
/// <param name="providerName">子节点providerName值</param>
/// <returns>返回成功与否布尔值</returns>
public static bool UpdateOrCreateConnectionString(string filename, string name, string connectionString, string providerName)
{
if (string.IsNullOrEmpty(filename))
{
throw new ArgumentNullException(filename);
}
if (string.IsNullOrEmpty(connectionString))
{
throw new ArgumentNullException(connectionString);
}
if (string.IsNullOrEmpty(providerName))
{
throw new ArgumentNullException(providerName);
}
var doc = new XmlDocument();
//加载配置文件
doc.Load(filename);
//得到[connectionStrings]节点
var node = doc.SelectSingleNode("//connectionStrings");
try
{
//得到[connectionStrings]节点中关于Name的子节点
if (node != null)
{
XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name='" + name + "']");
if (element != null)
{
//存在则更新子节点
element.SetAttribute("connectionString", connectionString);
element.SetAttribute("providerName", providerName);
}
else
{
//不存在则新增子节点
var subElement = doc.CreateElement("add");
subElement.SetAttribute("name", name);
subElement.SetAttribute("connectionString", connectionString);
subElement.SetAttribute("providerName", providerName);
node.AppendChild(subElement);
}
}
//保存至配置文件(方式二)
doc.Save(filename);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return true;
}

10.删除[appSettings]节点中包含Key值的子节点,返回成功与否布尔值:

        /// <summary>
/// 删除[appSettings]节点中包含Key值的子节点,返回成功与否布尔值
/// </summary>
/// <param name="filename">配置文件路径</param>
/// <param name="key">要删除的子节点Key值</param>
/// <returns>返回成功与否布尔值</returns>
public static bool DeleteByKey(string filename, string key)
{
if (string.IsNullOrEmpty(filename))
{
throw new ArgumentNullException(filename);
}
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(key);
}
var doc = new XmlDocument();
//加载配置文件
doc.Load(filename);
//得到[appSettings]节点
var node = doc.SelectSingleNode("//appSettings");
//得到[appSettings]节点中关于Key的子节点
if (node != null)
{
var element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
if (element != null)
{
//存在则删除子节点
if (element.ParentNode != null) element.ParentNode.RemoveChild(element);
}
}
try
{
//保存至配置文件(方式一)
using (var xmlwriter = new XmlTextWriter(filename, null))
{
xmlwriter.Formatting = Formatting.Indented;
doc.WriteTo(xmlwriter);
xmlwriter.Flush();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return true;
}

11.删除[connectionStrings]节点中包含name值的子节点,返回成功与否布尔值:

        /// <summary>
/// 删除[connectionStrings]节点中包含name值的子节点,返回成功与否布尔值
/// </summary>
/// <param name="filename">配置文件路径</param>
/// <param name="name">要删除的子节点name值</param>
/// <returns>返回成功与否布尔值</returns>
public static bool DeleteByName(string filename, string name)
{
if (string.IsNullOrEmpty(filename))
{
throw new ArgumentNullException(filename);
}
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException(name);
}
var doc = new XmlDocument();
//加载配置文件
doc.Load(filename);
//得到[connectionStrings]节点
var node = doc.SelectSingleNode("//connectionStrings");
//得到[connectionStrings]节点中关于Name的子节点
if (node != null)
{
var element = (XmlElement)node.SelectSingleNode("//add[@name='" + name + "']");
if (element != null)
{
//存在则删除子节点
node.RemoveChild(element);
}
}
try
{
//保存至配置文件(方式二)
doc.Save(filename);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return true;
}

以上对System.Configuration类的几种常用方法做了简单说明,也提供了几种较为常用的操作方法,希望对在项目中需要使用到配置文件的开发人员有用。

DotNet程序配置文件的更多相关文章

  1. .NET 多个程序配置文件合并到主app.config

    .NET 多个程序配置文件合并到主app.config

  2. C# 应用程序配置文件操作

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

  3. C#/ASP.NET应用程序配置文件app.config/web.config的增、删、改操作

    原文 http://www.cnblogs.com/codealone/archive/2013/09/22/3332607.html 应用程序配置文件,对于asp.net是 web.config,对 ...

  4. 无法为具有固定名称“MySql.Data.MySqlClient”的 ADO.NET 提供程序加载在应用程序配置文件中注册的实体框架提供程序类型“MySql.Data.MySqlClient.MySqlProviderServices,MySql.Data.Entity.EF6”

    "System.InvalidOperationException"类型的未经处理的异常在 mscorlib.dll 中发生 其他信息: 无法为具有固定名称"MySql. ...

  5. C# 中的 ConfigurationManager类引用方法应用程序配置文件App.config的写法

    c#添加了Configuration;后,竟然找不到 ConfigurationManager 这个类,后来才发现:虽然引用了using System.Configuration;这个包,但是还是不行 ...

  6. 无法为具有固定名称“System.Data.SqlClient”的 ADO.NET 提供程序加载在应用程序配置文件中注册的实体框架提供程序类型“System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer”。请确保使用限定程序集的名称且该程序集对运行的应用程序可用。有关详细信息,请参阅 http://go.m

    Windows服务中程序发布之后会如下错误: 无法为具有固定名称“System.Data.SqlClient”的 ADO.NET 提供程序加载在应用程序配置文件中注册的实体框架提供程序类型“Syste ...

  7. MVC开发中的常见错误-02-在应用程序配置文件中找不到名为“OAEntities”的连接字符串。

    在应用程序配置文件中找不到名为“OAEntities”的连接字符串. 分析原因:由于Model类是数据库实体模型,通过从数据库中引用的方式添加实体,所以会自动产生一个数据库连接字符串,而程序运行到此, ...

  8. C#/ASP.NET应用程序配置文件app.config/web.config的增、删、改操作,无法为请求的 Configuration 对象创建配置文件。

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

  9. 关于使用Entity Framework时遇到的问题 未找到具有固定名称“System.Data.SqlClient”的 ADO.NET 提供程序的实体框架提供程序。请确保在应用程序配置文件的“entityFramework”节中注册了该提供程序

    问题描述: 使用Entity Framework获取数据时报以下错误: 未找到具有固定名称“System.Data.SqlClient”的 ADO.NET 提供程序的实体框架提供程序.请确保在应用程序 ...

随机推荐

  1. 简谈百度坐标反转至WGS84的三种思路

    文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/ 1.背景 基于百度地图进行数据展示是目前项目中常见场景,但是因为百度地图 ...

  2. 关于自己写C++的一点风格

    现在,我学了很长时间的C++,但是自己就是无法精通.许多知识是入门书上没有的.现在写C++最重要的就是风格问题. 我现在的C++风格: 把自己所有的东西都放在一个名称空间下. 没有全局的函数,有的函数 ...

  3. 旺财速啃H5框架之Bootstrap(一)

    接下来的时间里,我将和大家一起对当前非常流行的前端框架Bootstrap进行速度的学习,以案例的形式.对刚开始想学习Bootstrap的同学而找不着边的就很有帮助了.如果你想详细的学习Bootstra ...

  4. redis 学习笔记(1)

    redis持久化 snapshot数据快照(rdb) 这是一种定时将redis内存中的数据写入磁盘文件的一种方案,这样保留这一时刻redis中的数据镜像,用于意外回滚.redis的snapshot的格 ...

  5. Hawk 5. 数据库系统

    Hawk在设计之初,就是以弱schema风格定义的.没有严格的列名和列属性.用C#这样的静态强类型语言编写Hawk,其实并不方便.但弱schema让Hawk变得更灵活更强大. 因此,Hawk虽然之前支 ...

  6. Maven搭建SpringMVC+Hibernate项目详解 【转】

    前言 今天复习一下SpringMVC+Hibernate的搭建,本来想着将Spring-Security权限控制框架也映入其中的,但是发现内容太多了,Spring-Security的就留在下一篇吧,这 ...

  7. SharePoint 2016 必备组件离线安装介绍

    前言 SharePoint 必备组件安装,一直以来都是SharePoint安装过程中的最大的坑,尤其是不能联网的服务器.博主在这里简单介绍一下离线安装过程,并附组件包下载以及安装命令,并且在windo ...

  8. Mysql - 增删改

    因为项目原因, mysql用了两年了, 但是一直都未曾去总结过. 最近也是领导让总结项目, 才想起把mysql的使用小结一下. 一. Create 1. 单条插入, sql格式: insert int ...

  9. 企业shell面试题:获取51CTO博客列表倒序排序考试题

    #!/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin HTMLFILE=/home/oldboy/ht ...

  10. Linux字符设备驱动框架

    字符设备是Linux三大设备之一(另外两种是块设备,网络设备),字符设备就是字节流形式通讯的I/O设备,绝大部分设备都是字符设备,常见的字符设备包括鼠标.键盘.显示器.串口等等,当我们执行ls -l ...