当前位置: 首页 > 编程日记 > 正文

配置文件app.config

无论对于客户端程序还是web应用程序,配置文件的作用不言而喻,现总结用法如下:

1. 创建配置节类

必须创建继承自ConfigurationSection的对象才能进行配置数据读写操作,ConfigurationSection提供了索引器用来获取和设置配置数据,需要注意的是拥有ConfigurationProperty特性的属性才会被存储,并且名称要保持大小写完全一致,如下面的代码中,所有的"id"必须保持一样。

class ConfigSectionData : ConfigurationSection
{
  [ConfigurationProperty("id")]
  public int Id
  {
    get { return (int)this["id"]; }
    set { this["id"] = value; }
  }

[ConfigurationProperty("time")]
  public DateTime Time
  {
    get { return (DateTime)this["time"]; }
    set { this["time"] = value; }
  }
}

2. 创建配置文件操作对象

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

ConfigSectionData data = new ConfigSectionData();
data.Id = 1000;
data.Time = DateTime.Now;

config.Sections.Add("add", data);
config.Save(ConfigurationSaveMode.Minimal);

上面的例子是操作 app.config,在根节点(configuration)下写入名称为"add"的配置数据。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="add" type="ConsoleApplication1.ConfigSectionData, ... />
  </configSections>
  <add id="1000" time="02/18/2006 21:51:06" />
</configuration>

需要注意的 VS2005 在IDE模式下会将信息写入 *.vshost.exe.config,并且在程序关闭时覆写该文件,因此您可能看不到您写入的配置数据,只要在资源管理其中执行 *.exe 文件,您就可以在 *.exe.config 文件中看到结果了。

如果我们需要操作非缺省配置文件,可以使用ExeConfigurationFileMap对象。

ExeConfigurationFileMap file = new ExeConfigurationFileMap();
file.ExeConfigFilename = "test.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);

ConfigSectionData data = new ConfigSectionData();
data.Id = 1000;
data.Time = DateTime.Now;

config.Sections.Add("add", data);
config.Save(ConfigurationSaveMode.Minimal);

如果我们不希望在根节点下写入配置数据,可以使用ConfigurationSectionGroup对象。

ExeConfigurationFileMap file = new ExeConfigurationFileMap();
file.ExeConfigFilename = "test.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);

ConfigSectionData data = new ConfigSectionData();
data.Id = 1000;
data.Time = DateTime.Now;

config.SectionGroups.Add("group1", new ConfigurationSectionGroup());
config.SectionGroups["group1"].Sections.Add("add", data);

config.Save(ConfigurationSaveMode.Minimal);

下面就是生成的配置文件。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="group1" type="System.Configuration.ConfigurationSectionGroup, ... >
      <section name="add" type="ConsoleApplication1.ConfigSectionData, ... />
    </sectionGroup>
  </configSections>
  <group1>
    <add id="1000" time="02/18/2006 22:01:02" />
  </group1>
</configuration>

3. 读取配置文件

ExeConfigurationFileMap file = new ExeConfigurationFileMap();
file.ExeConfigFilename = "test.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);

ConfigSectionData data = config.SectionGroups["group1"].Sections["add"] as ConfigSectionData;
//ConfigSectionData data = config.Sections["add"] as ConfigSectionData; // 从根节读取

if (data != null)
{
  Console.WriteLine(data.Id);
  Console.WriteLine(data.Time);
}

4. 写配置文件

在写入 ConfigurationSectionGroup 和 ConfigurationSection 前要判断同名配置是否已经存在,否则会写入失败。
另外如果配置文件被其他Configuration对象修改,则保存会失败,并抛出异常。建议采用Singleton模式。

ExeConfigurationFileMap file = new ExeConfigurationFileMap();
file.ExeConfigFilename = "test.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);

ConfigSectionData data = new ConfigSectionData();
data.Id = 2000;
data.Time = DateTime.Now;

ConfigurationSectionGroup group1 = config.SectionGroups["group1"];
if (group1 == null)
  config.SectionGroups.Add("group1", new ConfigurationSectionGroup());

ConfigurationSection data = group1.Sections["add"] as config;
if (add == null)
  config.SectionGroups["group1"].Sections.Add("add", data);
else
{
  group1.Sections.Remove("add");
  group1.Sections.Add("add", data);

// 或者直接修改原配置对象,前提是类型转换要成功。
  //ConfigSectionData configData = add as ConfigSectionData;
  //configData.Id = data.Id;
  //configData.Time = data.Time;
}

config.Save(ConfigurationSaveMode.Minimal);

5. 删除配置节

删除ConfigurationSectionGroup
config.SectionGroups.Remove("group1");
//config.SectionGroups.Clear();

config.Save(ConfigurationSaveMode.Minimal);

删除ConfigurationSection
config.Sections.Remove("add1");
//config.Sections.Clear();

if (config.SectionGroups["group1"] != null)
{
  config.SectionGroups["group1"].Sections.Remove("add2");
  //config.SectionGroups["group1"].Sections.Clear();
}

config.Save(ConfigurationSaveMode.Minimal);

6. 其他

可以使用 ConfigurationManager.OpenMachineConfiguration() 来操作 Machine.config 文件。
或者使用 System.Web.Configuration 名字空间中的 WebConfigurationManager 类来操作 ASP.net 配置文件。
ConfigurationManager还提供了AppSettings、ConnectionStrings、GetSection()等便捷操作。

转载于:https://www.cnblogs.com/flyinghigher/archive/2010/06/28/1766933.html

相关文章:

windows远程桌面如果超出最大连接数, 使用命令行mstsc /console登录即可

远程桌面如果超出最大连接数, 使用命令行mstsc /console登录即可。 &#xff08;也可以用 mstsc /admin&#xff09; 可以在运行里使用mstsc /console /v:IP:远程端口即可强制登录; 如果直接在远程桌面连接端使用就直接输入/console /v:IP:远程端口. 如&#xff1a;mstsc /cons…

AppiumForWin安装

尝试安装Windows版本的Appium参考&#xff1a;http://www.cnblogs.com/fnng/p/4540731.html第一步&#xff1a;安装nodehttps://nodejs.org/en/安装成功后使用&#xff1a;node -v&#xff0c;进行验证第二步&#xff1a;安装Appium下面的方法失败&#xff1a;原因下载不成功&a…

prometheus--初见

什么是prometheus Prometheus&#xff08;普罗米修斯&#xff09;是一个开源系统监控和警报工具&#xff0c;最初是在SoundCloud建立的。自2012年成立以来&#xff0c;许多公司和组织都采用了普罗米修斯&#xff0c;该项目拥有一个非常活跃的开发者和用户社区。它现在是一个独立…

JavaScript时间日期格式化

/** 时间对象的格式化;*/ Date.prototype.format function(format) {/** eg:format"YYYY-MM-dd hh:mm:ss";*/var o {"M" :this.getMonth() 1, // month"d" :this.getDate(), // day"h" :this.getHours(), // hour"m" :th…

Hello World

作为所有编程语言的起始阶段&#xff0c;HELLO WORLD占据着无法改变的地位&#xff0c;所有中/英/法/德/美……版本的编程教材中&#xff0c;HELLO WORLD总是作为第一个TEST记录于书本之中&#xff0c;所有的编程第一步就在于此了&#xff01;经典之中的经典&#xff01;HELLO …

POJ 1144 Network (求割点)

题意&#xff1a; 给定一幅无向图&#xff0c; 求出图的割点。 割点模板&#xff1a;http://www.cnblogs.com/Jadon97/p/8328750.html 分析&#xff1a; 输入有点麻烦&#xff0c; 用stringsteam 会比较简单 #include<cstdio> #include<iostream> #include<queu…

mongoose简单使用

介绍&安装 官网&#xff1a;http://www.mongoosejs.net/ npm i -S mongoose 使用 1.连接mongodb&创建模型 var mongoose require(mongoose)​//1、连接mongodb mongoose.connect(mongodb://localhost/test)​//2、设置文档结构var userSchema new mongoose.Schema…

Codeforces Round #563 (Div. 2)/CF1174

Codeforces Round #563 (Div. 2)/CF1174 CF1174A Ehab Fails to Be Thanos 其实就是要\(\sum\limits_{i1}^n a_i\)与\(\sum\limits_{n1}^{2n}a_i\)差值最大&#xff0c;排一下序就好了 CF1174B Ehab Is an Odd Person 一个显然的结论就是如果至少有一个奇数和一个偶数&#xff…

Enterprise Architect 中文经典教程

一、Enterprise Architect简介Enterprise Architect是一个对于软件系统开发有着极好支持的CASE软件&#xff08;Computer Aided Software Engineering&#xff09;。EA不同于普通的UML画图工具&#xff08;如VISIO&#xff09;&#xff0c;它将支撑系统开发的全过程。在需求分析…

[WebDev]Web 开发与设计师速查手册大全

Cheat Sheet 一词在中文中并没有很贴切的对译&#xff0c;大概是考试作弊条一类的东西&#xff0c;这要求 Cheat Sheet 必须短小精悍又覆盖广泛&#xff0c;作为 Web 开发与设计师&#xff0c;免不了在工作时查询大量资料&#xff0c;某个 Web 色值&#xff0c;某个 JavaScript…

android中的回调

1、引子 android中的回调最经典的就是点击事件设置监听&#xff08;一般通过switch&#xff08;v.getId()&#xff09;&#xff09;这里写个最主要的 btn_rigister.setOnClickListener(new View.OnClickListener() {Overridepublic void onClick(View view) {// TODO log in} }…

nodejs回调函数理解

回调实例 问题&#xff1a;想要得到一秒后 计算出的结果 //错误写法function add(x,y) {console.log(1);setTimeout(function () {console.log(2);var ret x y;return ret;},1000);console.log(3)}console.log(add(10,20))添加一个函数作为参数&#xff0c;将计算出来的结果传…

C# 运算符的优先级

优先级由高到低 --(用作前缀); ; -(一元); () ; ! ; ~ * ; / ; % ; - <<; >> < ; > ; < ; > ; ! & ^ | && || ; * ; / ; % ; ; - ; << ; >> ; & ; ^ ;| --(作后缀);转载于:https://www.cnblogs.com/h…

Service Manager 的系统要求

以下各节包含有关 Service Manager 的硬件和软件要求的信息&#xff0c;并基于以下环境。System Center Service Manager 2010 已经过测试&#xff0c;并且正在使用一个支持 80 到 100 个并发 Service Manager 控制台的 Service Manager 管理服务器&#xff0c;测试根据本指南中…

读Lodash源码——chunk.js

The time is out of joint: O cursed spite, That ever I was born to set it right. --莎士比亚 最艰难的第一步 最近学习遇到了些障碍&#xff0c;浮躁浮躁又浮躁。很难静下心来做一件事&#xff0c;北京的寒风也难以让我冷静下来. 之前一直很想找个源码读读&#xff0c;太懒…

使用相对路径时,./、../、../../,代表的什么?

./ 当前目录。../ 父级目录。/ 根目录。 举个栗子&#xff1a; 页面引入js、css等文件&#xff1a; 1.如果about.jsp页面想引入common.css文件&#xff1a; 以about.jsp为基点寻找 直到 和static文件在同一级&#xff1b; 2.如果引入的外部css、js文件又引入image等时&#x…

asyncawait

简单理解 async async就是将方法变成异步 await 是等待异步方法的执行完成&#xff0c;可以获取异步方法里面的数据&#xff0c;但必须得用在异步方法(async)里面 创建异步方法 定义一个普通方法&#xff0c;返回值是一个字符串 function getData() {return 这是一个数据;}co…

引起路由器重启的“元凶”

文章出处&#xff1a;www.net1980.com在我们的日常维护中&#xff0c;偶然会遇到一些路由器自动重启的故障。那么大家都会自然地猜测到是否设备已经运行一段长时间&#xff0c;设备稳定性开始减低。或者可能有工作人员把电源拨松了&#xff0c;又或者设备负荷过重等原因。那么究…

python csv.reader参数指定

转载于:https://www.cnblogs.com/mahailuo/p/8375997.html

xBIM 实战01 在浏览器中加载IFC模型文件

系列目录 【已更新最新开发文章&#xff0c;点击查看详细】 一、创建Web项目打开VS&#xff0c;新建Web项目&#xff0c;选择 .NET Framework 4.5选择一个空的项目新建完成后&#xff0c;项目结构如下&#xff1a; 二、添加webServer访问文件类型由于WexXplorer 加载的是 .w…

node 判断文件夹是否存在

判断文件夹是否存在 let filePath path.join(__dirname,../)/download_tmp/fs.exists(filePath, function(exists) {if(!exists){fs.mkdir(filePath,function (err) {if(err){console.log(err)}})}});生成excle文件到本地 业务要求&#xff1a;生成excle文件到本地的路径 #安装…

IE9 : DOM Exception: INVALID_CHARACTER_ERR (5)

以下代码在IE8下运行通过&#xff0c;在IE9中出错&#xff1a;document.createElement(<iframe id"yui-history-iframe" src"../../images/defaults/transparent-pixel.gif" style"position:absolute;top:0;left:0;width:1px;height:1px;visibilit…

数字家庭开发者中心

数字家庭开发者中心 http://www.adobe.com/devnet/devices/digital_home.html转载于:https://www.cnblogs.com/kobo/archive/2010/07/06/1772136.html

LeetCode 1021:Remove Outermost Parentheses

C语言 char * removeOuterParentheses(char * S){int len strlen(S);int j 0;int sum 0;for(int i 0; i < len; i){if (S[i] (){sum 1;}else if (S[i] )){sum - 1;}if (S[i] ( && sum > 1){S[j] (;j;}else if (S[i] ) && sum > 0){S[j] );…

Koa实现下载excel

Koa实现下载excel #安装 node-xlsx npm install node-xlsx --save实现思路&#xff1a;将生成的excel文件流返回到前端 routes router.get(/mp/push_excle, async (ctx, next) > {await Push.pushGroupExcel(ctx).then(function(res) {// let path resctx.set(Content-Ty…

使用 雨林木风 Ghost XP SP3 装机版 YN9.9 安装 Win7 (SP1)

下载Win7 SP1一段时间了&#xff0c;一直没来安装&#xff0c;今天来安装&#xff0c;由于没有DVD刻录机&#xff0c;不能做成光盘安装发现还不是那么方便。后面想到用雨林木风PE光盘来安装&#xff0c;一步一步 【下面假设是将Win7 (SP1) 将要安装到 C: 盘中】 首先使用 雨林木…

2010中国大陆×××指南,满足你的欲望!

中国大陆指南&#xff0c;满足你的欲望&#xff01; 川渝--椒麻鸡,怪味鸡,棒棒鸡,口水鸡,罐罐鸡,辣子鸡 广东--太爷鸡,越秀鸡,花雕鸡,板栗焖仔鸡,客家盐局鸡,湛江鸡,清远鸡广西--桂林黄焖鸡,梧州纸包鸡,啤酒鸡,泉水鸡 山东--沂蒙光棍鸡,德州扒鸡 云南--汽锅鸡,柴把鸡 贵州-…

iframe元素內嵌页面如何去掉继承的html及body背景色/背景图片

【1】去掉背景色&#xff1a;添加如左的样式 filter:Chroma(Colorwhite); <iframe name"Conframe" id"Conframe" name"back" style"background:#2397E2filter:Chroma(Colorwhite)"></iframe> 转载于:https://www.cn…

ListView style

步骤一&#xff1a;在使用的ListView的activiey里使用android&#xff1a;theme“style/Theme的名字” 步骤二&#xff1a;创建Themes.xml 在Themes.xml里定义的使用的样式。如&#xff1a; 步骤三&#xff1a;在themes.xml使用了styles.xml定义的listView的属性&#xff0c;创…

数据结构和算法-栈

栈可以分为 顺序栈: 数组实现链式栈: 链表实现空间复杂度 栈的空间复杂度: 有一个n个元素的栈, 在入栈和出栈过程中, 只需要存储一个临时变量存储空间, 所以空间复杂度是O(1) 并不是说栈有n个元素, 空间复杂度就是O(n), 而是指除了原本的空间外, 算法需要的额外空间 栈要满足后…