在实际的项目开发中,对于项目的相关信息的配置较多,在.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. Angular2入门系列教程4-服务

    上一篇文章 Angular2入门系列教程-多个组件,主从关系 在编程中,我们通常会将数据提供单独分离出来,以免在编写程序的过程中反复复制粘贴数据请求的代码 Angular2中提供了依赖注入的概念,使得 ...

  2. 消息队列——RabbitMQ学习笔记

    消息队列--RabbitMQ学习笔记 1. 写在前面 昨天简单学习了一个消息队列项目--RabbitMQ,今天趁热打铁,将学到的东西记录下来. 学习的资料主要是官网给出的6个基本的消息发送/接收模型, ...

  3. C++内存对齐总结

    大家都知道,C++空类的内存大小为1字节,为了保证其对象拥有彼此独立的内存地址.非空类的大小与类中非静态成员变量和虚函数表的多少有关. 而值得注意的是,类中非静态成员变量的大小与编译器内存对齐的设置有 ...

  4. MVVM框架从WPF移植到UWP遇到的问题和解决方法

    MVVM框架从WPF移植到UWP遇到的问题和解决方法 0x00 起因 这几天开始学习UWP了,之前有WPF经验,所以总体感觉还可以,看了一些基础概念和主题,写了几个测试程序,突然想起来了前一段时间在W ...

  5. AutoMapper:Unmapped members were found. Review the types and members below. Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type

    异常处理汇总-后端系列 http://www.cnblogs.com/dunitian/p/4523006.html 应用场景:ViewModel==>Mode映射的时候出错 AutoMappe ...

  6. 【翻译】MongoDB指南/CRUD操作(三)

    [原文地址]https://docs.mongodb.com/manual/ CRUD操作(三) 主要内容: 原子性和事务(Atomicity and Transactions),读隔离.一致性和新近 ...

  7. 用html5的canvas和JavaScript创建一个绘图程序

    本文将引导你使用canvas和JavaScript创建一个简单的绘图程序. 创建canvas元素 首先准备容器Canvas元素,接下来所有的事情都会在JavaScript里面. <canvas ...

  8. .net 分布式架构之分布式缓存中间件

    开源git地址: http://git.oschina.net/chejiangyi/XXF.BaseService.DistributedCache 分布式缓存中间件  方便实现缓存的分布式,集群, ...

  9. Java类访问权限修饰符

    一.概要 通过了解Java4种修饰符访问权限,能够进一步完善程序类,合理规划权限的范围,这样才能减少漏洞.提高安全性.具备表达力便于使用. 二.权限表 修饰符 同一个类 同一个包 不同包的子类 不同包 ...

  10. Mysql 学习之基础操作

    一.表复制 1.复制表结构    将表hello的结构复制一份为表hello3 2.复制数据 a.如果两张表的结构一样且你要复制所有列的数据 mysql> insert into hello3 ...