DotNet程序配置文件
在实际的项目开发中,对于项目的相关信息的配置较多,在.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程序配置文件的更多相关文章
- .NET 多个程序配置文件合并到主app.config
.NET 多个程序配置文件合并到主app.config
- C# 应用程序配置文件操作
应用程序配置文件,对于asp.net是 web.config对于WINFORM程序是 App.Config(ExeName.exe.config). 配置文件,对于程序本身来说,就是基础和依据,其本质 ...
- C#/ASP.NET应用程序配置文件app.config/web.config的增、删、改操作
原文 http://www.cnblogs.com/codealone/archive/2013/09/22/3332607.html 应用程序配置文件,对于asp.net是 web.config,对 ...
- 无法为具有固定名称“MySql.Data.MySqlClient”的 ADO.NET 提供程序加载在应用程序配置文件中注册的实体框架提供程序类型“MySql.Data.MySqlClient.MySqlProviderServices,MySql.Data.Entity.EF6”
"System.InvalidOperationException"类型的未经处理的异常在 mscorlib.dll 中发生 其他信息: 无法为具有固定名称"MySql. ...
- C# 中的 ConfigurationManager类引用方法应用程序配置文件App.config的写法
c#添加了Configuration;后,竟然找不到 ConfigurationManager 这个类,后来才发现:虽然引用了using System.Configuration;这个包,但是还是不行 ...
- 无法为具有固定名称“System.Data.SqlClient”的 ADO.NET 提供程序加载在应用程序配置文件中注册的实体框架提供程序类型“System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer”。请确保使用限定程序集的名称且该程序集对运行的应用程序可用。有关详细信息,请参阅 http://go.m
Windows服务中程序发布之后会如下错误: 无法为具有固定名称“System.Data.SqlClient”的 ADO.NET 提供程序加载在应用程序配置文件中注册的实体框架提供程序类型“Syste ...
- MVC开发中的常见错误-02-在应用程序配置文件中找不到名为“OAEntities”的连接字符串。
在应用程序配置文件中找不到名为“OAEntities”的连接字符串. 分析原因:由于Model类是数据库实体模型,通过从数据库中引用的方式添加实体,所以会自动产生一个数据库连接字符串,而程序运行到此, ...
- C#/ASP.NET应用程序配置文件app.config/web.config的增、删、改操作,无法为请求的 Configuration 对象创建配置文件。
应用程序配置文件,对于asp.net是 web.config,对于WINFORM程序是 App.Config(ExeName.exe.config). 配置文件,对于程序本身来说,就是基础和依据,其本 ...
- 关于使用Entity Framework时遇到的问题 未找到具有固定名称“System.Data.SqlClient”的 ADO.NET 提供程序的实体框架提供程序。请确保在应用程序配置文件的“entityFramework”节中注册了该提供程序
问题描述: 使用Entity Framework获取数据时报以下错误: 未找到具有固定名称“System.Data.SqlClient”的 ADO.NET 提供程序的实体框架提供程序.请确保在应用程序 ...
随机推荐
- 分享一个SQLSERVER脚本(计算数据库中各个表的数据量和每行记录所占用空间)
分享一个SQLSERVER脚本(计算数据库中各个表的数据量和每行记录所占用空间) 很多时候我们都需要计算数据库中各个表的数据量和每行记录所占用空间 这里共享一个脚本 CREATE TABLE #tab ...
- 本人提供微软系.NET技术顾问服务,欢迎企业咨询!
背景: 1:目前微软系.NET技术高端人才缺少. 2:企业很难直接招到高端技术人才. 3:本人提供.NET技术顾问,保障你的产品或项目在正确的技术方向. 技术顾问服务 硬服务项: 1:提供技术.决策. ...
- [C#] 软硬结合第二篇——酷我音乐盒的逆天玩法
1.灵感来源: LZ是纯宅男,一天从早上8:00起一直要呆在电脑旁到晚上12:00左右吧~平时也没人来闲聊几句,刷空间暑假也没啥动态,听音乐吧...~有些确实不好听,于是就不得不打断手头的工作去点击下 ...
- Android 获取meta-data中的数据
在 Android 的 Mainfest 清单文件中,Application,Activity,Recriver,Service 的节点中都有这个的存在.很多时候我们可以通过 meta-data 来配 ...
- mysql学习之 sql语句的技巧及优化
一.sql中使用正则表达式 select name,email from user where email Regexp "@163[.,]com$"; sql语句中使用Regex ...
- PHP获取上个月最后一天的一个容易忽略的问题
正常来说,PHP是有一个很方便的函数可以获取上个月时间的 strtotime (PHP 4, PHP 5, PHP 7) strtotime - 将任何英文文本的日期时间描述解析为 Unix 时间戳 ...
- Spring resource bundle多语言,单引号format异常
Spring resource bundle多语言,单引号format异常 前言 十一假期被通知出现大bug,然后发现是多语言翻译问题.法语中有很多单引号,单引号在format的时候出现无法匹配问题. ...
- js面向对象学习 - 对象概念及创建对象
原文地址:js面向对象学习笔记 一.对象概念 对象是什么?对象是“无序属性的集合,其属性可以包括基本值,对象或者函数”.也就是一组名值对的无序集合. 对象的特性(不可直接访问),也就是属性包含两种,数 ...
- Java中,异常的处理及抛出
首先我们需要知道什么是异常? 常通常指,你的代码可能在编译时没有错误,可是运行时会出现异常.比如常见的空指针异常.也可能是程序可能出现无法预料的异常,比如你要从一个文件读信息,可这个文件不存在,程序无 ...
- ES6之变量常量字符串数值
ECMAScript 6 是 JavaScript 语言的最新一代标准,当前标准已于 2015 年 6 月正式发布,故又称 ECMAScript 2015. ES6对数据类型进行了一些扩展 在js中使 ...