读语句:
String str = ConfigurationManager.AppSettings["DemoKey"];
写语句:
Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
cfa.AppSettings.Settings["DemoKey"].Value = "DemoValue";
cfa.Save();
配置文件内容格式:(app.config)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DemoKey" value="*" />
</appSettings>
</configuration>
System.Configuration.ConfigurationSettings.AppSettings["Key"];
但是现在FrameWork2.0已经明确表示此属性已经过时。并建议改为ConfigurationManager或
WebConfigurationManager。并且AppSettings属性是只读的,并不支持修改属性值.
但是要想调用ConfigurationManager必须要先在工程里添加system.configuration.dll程序集的引用。
添加引用后可以用 String str = ConfigurationManager.AppSettings["Key"]来获取对应的值了。
更新配置文件:
Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
cfa.AppSettings.Settings.Add("key", "Name") || cfa.AppSettings.Settings["BrowseDir"].Value = "name";
等等...
最后调用
cfa.Save();
当前的配置文件更新成功。 读写配置文件app.config
在.Net中提供了配置文件,让我们可以很方面的处理配置信息,这个配置是XML格式的。而且.Net中已经提供了一些访问这个文件的功能。
1、读取配置信息
下面是一个配置文件的具体内容:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="ConnenctionString" value="*" />
<add key="TmpPath" value="C:/Temp" />
</appSettings>
</configuration>
.net提供了可以直接访问<appsettings>(注意大小写)元素的方法,在这元素中有很多的子元素,这些子元素名称都是 “add”,有两个属性分别是“key”和“value”。一般情况下我们可以将自己的配置信息写在这个区域中,通过下面的方式进行访问:
string ConString=System.Configuration.ConfigurationSettings.AppSettings["ConnenctionString"];
在appsettings后面的是子元素的key属性的值,例如appsettings["connenctionstring"],我们就是访 问<add key="ConnenctionString" value="*" />这个子元素,它的返回值就是“*”,即value属性的值。
2、设置配置信息
如果配置信息是静态的,我们可以手工配置,要注意格式。如果配置信息是动态的,就需要我们写程序来实现。在.Net中没有写配置文件的功能,我们可以使用操作XML文件的方式来操作配置文件。下面就是一个写配置文件的例子。
private void SaveConfig(string ConnenctionString)
{
XmlDocument doc=new XmlDocument();
//获得配置文件的全路径
string strFileName=AppDomain.CurrentDomain.BaseDirectory.ToString()+"Code.exe.config";
doc.LOAd(strFileName);
//找出名称为“add”的所有元素
XmlNodeList nodes=doc.GetElementsByTagName("add");
for(int i=0;i<nodes.Count;i++)
{
//获得将当前元素的key属性
XmlAttribute att=nodes[i].Attributes["key"];
//根据元素的第一个属性来判断当前的元素是不是目标元素
if (att.Value=="ConnectionString")
{
//对目标元素中的第二个属性赋值
att=nodes[i].Attributes["value"];
att.Value=ConnenctionString;
break;
}
}
//保存上面的修改
doc.Save(strFileName);
} 通过程序实现读写配置文件的代码如下所示:
1 创建配置文件中的配置节所对应的类。该类必须继承自ConfigurationSection
public sealed class ConfigurationSections : ConfigurationSection
{
[ConfigurationProperty("filename", DefaultValue = "default.txt")]
public string FileName
{
get
{
return (string)this["filename"];
}
set
{
this["filename"] = value;
}
}
}
public sealed class BusinessSpaceConfiguration : ConfigurationSection
{
[ConfigurationProperty("filename")]
public string FileName
{
get
{
return (string)this["filename"];
}
set
{
this["filename"] = value;
}
}
}
2 创建配置文件代码
private static void WriteAppConfiguration()
{
try
{
ConfigurationSections configData = new ConfigurationSections();
configData.FileName = "abc.txt";
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.Sections.Remove("ConfigurationSections");
config.Sections.Add("ConfigurationSections", configData);
config.Save();
BusinessSpaceConfiguration bsconfigData = new BusinessSpaceConfiguration();
bsconfigData.FileName = "def.txt";
System.Configuration.Configuration config1 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config1.Sections.Remove("BusinessSpaceConfiguration");
config1.Sections.Add("BusinessSpaceConfiguration", bsconfigData);
config1.Save();
}
catch (Exception err)
{
Console.Write(err.Message);
}
}
3 生成的配置文件格式如下所示:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="BusinessSpaceConfiguration" type="ConsoleApplication1.BusinessSpaceConfiguration, ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<section name="ConfigurationSections" type="ConsoleApplication1.ConfigurationSections, ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</configSections>
<BusinessSpaceConfiguration filename="def.txt" />
<ConfigurationSections filename="abc.txt" />
</configuration>
3 读取应用程序配置文件
private static void ReadAppConfiguration()
{
ConfigurationSections obj1 = ConfigurationManager.GetSection("ConfigurationSections") as ConfigurationSections;
BusinessSpaceConfiguration obj2 = ConfigurationManager.GetSection("BusinessSpaceConfiguration") as BusinessSpaceConfiguration;
Console.WriteLine(obj1.FileName);
Console.WriteLine(obj2.FileName);
}
自定义应用程序配置文件(app.config)
1. 配置文件概述:
应用程序配置文件是标准的 XML 文件,XML 标记和属性是区分大小写的。它是可以按需要更改的,开发人员可以使用配置文件来更改设置,而不必重编译应用程序。配置文件的根节点是 configuration。我们经常访问的是appSettings,它是由.Net预定义配置节。我们经常使用的配置文件的架构是象下面的形式。先大 概有个印象,通过后面的实例会有一个比较清楚的认识。下面的“配置节”可以理解为进行配置一个XML的节点。
常见配置文件模式:
<configuration>
<configSections> //配置节声明区域,包含配置节和命名空间声明
<section> //配置节声明
<sectionGroup> //定义配置节组
<section> //配置节组中的配置节声明
<appSettings> //预定义配置节
<Custom element for configuration section> //配置节设置区域
2. 只有appSettings节的配置文件及访问方法
下面是一个最常见的应用程序配置文件的例子,只有appSettings节。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="connectionstring" value="User ID=sa;Data Source=.;Password=;Initial Catalog=test;Provider=SQLOLEDB.1;" />
<add key="TemplatePATH" value="Template" />
</appSettings>
</configuration>
下面来看看这样的配置文件如何方法。
string _connectionString=ConfigurationSettings.AppSettings["connectionstring"];
使用ConfigurationSettings类的静态属性AppSettings就可以直接方法配置文件中的配置信息。这个属性的类型是NameValueCollection。
/3. 自定义配置文件
3.1 自定义配置节
一个用户自定义的配置节,在配置文件中分为两部分:一是在<configSections></ configSections>配置节中声明配置节(上面配置文件模式中的“<section>”),另外是 在<configSections></ configSections >之后设置配置节(上面配置文件模式中的“<Custom element for configuration section>”),有点类似一个变量先声明,后使用一样。声明一个配置文件的语句如下:
<section name=" " type=" "/>
<section>:声明新配置节,即可创建新配置节。
name:自定义配置节的名称。
type:自定义配置节的类型,主要包括System.Configuration.SingleTagSectionHandler、 System.Configuration.DictionarySectionHandler、 System.Configuration.NameValueSectionHandler。
不同的type不但设置配置节的方式不一样,最后访问配置文件的操作上也有差异。下面我们就举一个配置文件的例子,让它包含这三个不同的type。 <?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="Test1" type="System.Configuration.SingleTagSectionHandler"/>
<section name="Test2" type="System.Configuration.DictionarySectionHandler"/>
<section name="Test3" type="System.Configuration.NameValueSectionHandler" />
</configSections> <Test1 setting1="Hello" setting2="World"/>
<Test2>
<add key="Hello" value="World" />
</Test2>
<Test3>
<add key="Hello" value="World" />
</Test3>
</configuration>
我们对上面的自定义配置节进行说明。在声明部分使用<section name="Test1" type="System.Configuration.SingleTagSectionHandler"/>声明了一个配置节它的名字叫 Test1,类型为SingleTagSectionHandler。在设置配置节部分使用 <Test1 setting1="Hello" setting2="World"/>设置了一个配置节,它的第一个设置的值是Hello,第二个值是World,当然还可以有更多。其它的两个配 置节和这个类似。
下面我们看在程序中如何访问这些自定义的配置节。我们用过ConfigurationSettings类的静态方法GetConfig来获取自定义配置节的信息。
public static object GetConfig(string sectionName);
下面是访问这三个配置节的代码:
//访问配置节Test1
IDictionary IDTest1 = (IDictionary)ConfigurationSettings.GetConfig("Test1");
string str = (string)IDTest1["setting1"] +" "+(string)IDTest1["setting2"];
MessageBox.Show(str); //输出Hello World
//访问配置节Test1的方法2
string[] values1=new string[IDTest1.Count];
IDTest1.Values.CopyTo(values1,0);
MessageBox.Show(values1[0]+" "+values1[1]); //输出Hello World
//访问配置节Test2
IDictionary IDTest2 = (IDictionary)ConfigurationSettings.GetConfig("Test2");
string[] keys=new string[IDTest2.Keys.Count];
string[] values=new string[IDTest2.Keys.Count];
IDTest2.Keys.CopyTo(keys,0);
IDTest2.Values.CopyTo(values,0);
MessageBox.Show(keys[0]+" "+values[0]);
//访问配置节Test3
NameValueCollection nc=(NameValueCollection)ConfigurationSettings.GetConfig("Test3");
MessageBox.Show(nc.AllKeys[0].ToString()+" "+nc["Hello"]); //输出Hello World
通过上面的代码我们可以看出,不同的type通过GetConfig返回的类型不同,具体获得配置内容的方式也不一样。 配置节处理程序
返回类型 SingleTagSectionHandler
Systems.Collections.IDictionary
DictionarySectionHandler
Systems.Collections.IDictionary
NameValueSectionHandler
Systems.Collections.Specialized.NameValueCollection
3.2 自定义配置节组
配置节组是使用<sectionGroup>元素,将类似的配置节分到同一个组中。配 置节组声明部分将创建配置节的包含元素,在<configSections>元素中声明配置节组,并将属于该组的节置 于<sectionGroup>元素中。下面是一个包含配置节组的配置文件的例子:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="TestGroup">
<section name="Test" type="System.Configuration.NameValueSectionHandler"/>
</sectionGroup>
</configSections> <TestGroup>
<Test>
<add key="Hello" value="World"/>
</Test>
</TestGroup>
</configuration>
下面是访问这个配置节组的代码:
NameValueCollection nc=(NameValueCollection)ConfigurationSettings.GetConfig("TestGroup/Test");
MessageBox.Show(nc.AllKeys[0].ToString()+" "+nc["Hello"]); //输出Hello World

C#读取 *.exe.config的更多相关文章

  1. c# c/s 框架读取的配置文件时是app.exe.config

    c# c/s 框架读取的配置文件时是app.exe.config, 一般在bin中间中俄debug中或者Release中

  2. 从 exe.config 读取appSettings 中的配置数据

    右键解决方案,添加引用--> System.Configuration.dll 在exe.config 中添加数据 <appSettings> <add key=" ...

  3. 程序集、应用程序配置及App.config和YourSoft.exe.config .

    转自:http://www.cnblogs.com/luminji/archive/2010/10/21/1857339.html 什么是程序集 程序集标识属性 强名称的程序集 强名称工作原理 配置文 ...

  4. 用于获取或设置Web.config/*.exe.config中节点数据的辅助类

    1. 用于获取或设置Web.config/*.exe.config中节点数据的辅助类 /**//// <summary> /// 用于获取或设置Web.config/*.exe.confi ...

  5. [转]WinForm和WebForm下读取app.config web.config 中邮件配置的方法

    本文转自:http://blog.csdn.net/jinbinhan/article/details/1598386 1. 在WinForm下读取 App.config中的邮件配置语句如下: Con ...

  6. Debug目录、Release目录,bin目录、obj目录,vshost.exe.config文件、.exe.config文件分析【C#】

    原文地址:http://blog.csdn.net/itwit/article/details/6803338 今天写程序的时候,需要更改.exe.config文件中的引用的webservice地址, ...

  7. app.config *.exe.config 和*.vshost.exe.config基础学习

    一.问题描述 在使用config文件来保存一些参数,便于下次启动程序时自动加载上次设置的参数的功能时, 碰到个问题,vs2010下调试运行程序始终无法实现config记录上次参数值,而直接运行exe程 ...

  8. 宿主进程 [*.vshost.exe] & [*.vshost.exe.config]

    宿主进程 [*.vshost.exe] & [*.vshost.exe.config] pdb文件: 英文全称:Program Database File 中文全称:程序数据库 文件 Debu ...

  9. 【Core】.NET Core中读取App.config配置文件

    1.项目中添加App.config文件 因为.NET Core的项目本质是控制台应用,所以ConfigurationManager的API会去默认读取app.config配置文件,而不是web.con ...

随机推荐

  1. CSS基础-如何用border写三角形?

    1.常用的border的单值属性(border指的是边框.) /*边框样式属性*/ border-style: solid; /*边框颜色*/ border-color: #06a43a; /*边框宽 ...

  2. 微信小程序中的自定义组件(components)

     其实小程序开发很像vue和react的结合,数据绑定和setData  重新渲染页面的数据,最近发现连写组件都是很像,也是醉了,自我认为哈, 因为小程序可以将页面内的功能模块抽象成自定义组件,以便在 ...

  3. UVa 725 Division (枚举)

    题意 : 输入正整数n,按从小到大的顺序输出所有形如abcde/fghij = n的表达式,其中a-j恰好为数字0-9的一个排列(可以有前导0),2≤n≤79. 分析 : 最暴力的方法莫过于采用数组存 ...

  4. RPN

    训练: 特征图是51x39x256,对该图像的每点考虑9个窗口:三种候选面积(128,256,512) x 三种尺度(1:1,1:2,2:1).这些候选窗口称为anchors.如下图: 如果图片尺寸w ...

  5. 字符串处理工具StringUtils

    package yqw.java.util; import java.io.File;import java.text.ParseException;import java.text.SimpleDa ...

  6. Oracle锁处理脚本

    ----处理死锁进程--查看被锁住的表select b.owner,b.object_name,a.session_id,a.locked_mode from v$locked_object a,db ...

  7. 原型模式故事链(4)--JS执行上下文、变量提升、函数声明

    上一章:JS的数据类型 传送门:https://segmentfault.com/a/11... 好!话不多少,我们就开始吧.对变量提升和函数声明的理解,能让你更清楚容易的理解,为什么你的程序报错了~ ...

  8. sql 查询每天数据

    一 表 内数据存的是 ‘2017-09-08 15:13:59’这样格式 表 customer_mate_follow 时间字段 created_at   1, SELECT ,) as day, C ...

  9. db2缓冲池调优

    缓存池: 冲池是内存中的一块区域,db2会将用到数据放到缓冲池中提高性能.缓冲池太小,每次查询仍然要到磁盘中操作,达不到缓冲的效果.缓冲池太大,超出操作系统管理的限制,会导致数据库无法连接的错误. 缓 ...

  10. 如何让你的JS代码写的更漂亮

    感觉这篇文章总结的js的规范写法不错,拿来收藏.转自:https://mp.weixin.qq.com/s/AtR94IL9BW9EXOTnKOilmA 1. 按强类型风格写代码 JS是弱类型的,但是 ...