原文链接:https://blog.csdn.net/dbzhang800/article/details/7212420

System.Configuration 命名空间中的东西是为读写应用程序的配置数据服务的。

在Windows早期,程序使用 .ini 作为配置文件,后来开始鼓励大家使用注册表,到了.NET中,又回归到使用文件,只不过这次默认是xml格式的文件。

例子

 

 程序program.exe默认配置文件 program.exe.config 中的 "appSettings" 段

读写 program.exe.config 中的 "appSettings" 段

读写 program.exe.config 中的自定义字段 "QtSection"

读写 roaming 文件中的自定义字段"QtSection"

读写 任意位置的配置文件?

例子一

  • 配置文件 program.exe.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="first name" value="Debao" />
<add key="last name" value="Zhang" />
</appSettings>
</configuration>
  • 程序源码 program.cs
using System.Configuration;

namespace DbZhang800
{
public class TestSettings
{
public static void Main()
{
foreach (string key in ConfigurationManager.AppSettings)
{
string val = ConfigurationManager.AppSettings[key];
Console.WriteLine("{0}: {1}", key, val);
}
}
}
}

编译运行,结果如下:

E:\> csc program.cs
E:\> program.exe
first name: Debao
last name: Zhang

通过 ConfigurationManager.AppSettings 我们可以很方便地读取默认配置文件中的 appSettings 段。

例子二

前面是只读的,如果需要写入怎么办?

            Configuration appConf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
appConf.AppSettings.Settings.Add("Qt", "Quick");
appConf.Save();

编译运行(注,这是运行3次后的结果,每次都给Qt这个key增加了一项):

E:\> csc program.cs
E:\> program.exe
first name: Debao
last name: Zhang
Qt: Quick,Quick,Quick

此时的配置文件 program.exe.config 内容如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="first name" value="Debao" />
<add key="last name" value="Zhang" />
<add key="Qt" value="Quick,Quick,Quick" />
</appSettings>
</configuration>

例子三

看看读写自定义字段的情况。不操作appSettings,操作一个自定义的QtSection段

program.cs

  • 首先创建一个ConfigurationSection的派生类

  • 然后打开一个配置文件,通过该派生类进行操作
using System;
using System.Configuration; namespace DbZhang800
{
public sealed class QtSection : ConfigurationSection
{
[ConfigurationProperty("version", DefaultValue="4.4.0")]
public string Version
{
get
{
return (string)this["version"];
} set
{
this["version"] = value;
}
}
} public class TestSettings
{
public static void Main()
{
Configuration appConf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
QtSection qtsection;
if ((qtsection = (QtSection)appConf.Sections["QtSection"]) == null)
{
qtsection = new QtSection();
//qtsection.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser;
appConf.Sections.Add("QtSection", qtsection);
}
Console.WriteLine("Current: {0}", qtsection.Version);
qtsection.Version = "5.0.0";
appConf.Save(ConfigurationSaveMode.Full);
}
}
}

运行后,生成的配置文件如下:

program.exe.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="QtSection" type="DbZhang800.QtSection, Program, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" allowLocation="true" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" overrideModeDefault="Allow" restartOnExternalChanges="true" requirePermission="true" />
</configSections>
<QtSection version="5.0.0" />
</configuration>

注意:它在configSections自动添加了我们自定义段的一些信息。

例子四

前面的配置文件和应用程序在同一个目录下,如果不同用户需要不同的配置文件怎么办呢?

前面的例子中,OpenExeConfiguration 使用的参数是 None,该参数指定不同的级别

None

只使用程序默认配置文件

PerUserRoaming

也要使用用户 roam 文件

PerUserRoamingAndLocal

也要使用用户local 文件

在前一个例子基础上,我们把 None 改为 PerUserRoaming看看,结果... 运行时:

E:\TestSettings>program.exe
Current: 5.0.0 未处理的异常: System.Configuration.ConfigurationErrorsException: 执行 !QtSection
的配置节处理程序时出错。 ---> System.InvalidOperationException: 不能编辑已锁定的
ConfigurationSection 属性。
...

报出异常,无法将其写入到roaming文件,原因何在呢?

  • 就在于我们在xml文件看到的那个 MachineToApplication 属性,该段只能写入到machine和appplication级别的配置文件,无法写入用户配置文件。

我们需要在生成这个段的时候就添加一个 MachineToRoamingUser 属性

       public static void Main()
{
Configuration appConf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);
QtSection qtsection;
if ((qtsection = (QtSection)appConf.Sections["QtSection"]) == null)
{
qtsection = new QtSection();
qtsection.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToRoamingUser;
appConf.Sections.Add("QtSection", qtsection);
}
Console.WriteLine("Current: {0}", qtsection.Version);
qtsection.Version = "5.0.0";
Console.WriteLine(appConf.FilePath);
appConf.Save(ConfigurationSaveMode.Full);
}

这样,配置可以正常写入

C:\Users\dbzhang\AppData\Roaming\DbZhang800\Program.exe_Url_foycvmvcbx4tf51hrft53z11fmpo2kto\0.0.0.0\user.config

打开其他的配置文件:

  • ConfigurationManager.OpenExeConfiguration(string)

    • 这个东西,string 指定 exe 的路径(但不限于,该路径后会被自动添加一个 .config)
  • ConfigurationManager..::.OpenMachineConfiguration()

    • 位于%windir%\Microsoft.NET\Framework\version\config

例子五

操作其他的配置文件

比如,我要操作当前工作目录下的 abcd.config 这个文件,那么需要使用 OpenMappedExcConfiguration:

        public static void Main()
{
string path = System.IO.Path.Combine(Environment.CurrentDirectory, "abcd.config");
ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = path;
Configuration appConf = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None); QtSection qtsection;
if ((qtsection = (QtSection)appConf.Sections["QtSection"]) == null)
{
qtsection = new QtSection();
appConf.Sections.Add("QtSection", qtsection);
}
Console.WriteLine("Current: {0}", qtsection.Version);
qtsection.Version = "5.0.0";
appConf.Save(ConfigurationSaveMode.Full);
}

C#下.NET配置文件的使用(1)的更多相关文章

  1. 使用T4模板生成不同部署环境下的配置文件

    在开发企业级应用的时候,通常会有不同的开发环境,比如有开发环境,测试环境,正式环境,生产环境等.在一份代码部署到不同环境的时候,不同环境的配置文件可能需要根据目标环境不同而不同.比如在开发环境中,数据 ...

  2. SpringJUnit4加载类目录下(src)和WEF-INF目录下的配置文件

    路径说明: 一.加载类目录下的配置文件 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:ap ...

  3. 直接修改workspace下的配置文件与tomcat下的文件

    项目中直接修改workspace下的配置文件与tomcat下的文件,可是还有错误,例如修改了4个配置文件中的一个配置文件.经查如下: 直接修改workspace下的配置文件与tomcat下的文件,可能 ...

  4. T4模板生成不同部署环境下的配置文件

    使用T4模板生成不同部署环境下的配置文件 在开发企业级应用的时候,通常会有不同的开发环境,比如有开发环境,测试环境,正式环境,生产环境等.在一份代码部署到不同环境的时候,不同环境的配置文件可能需要根据 ...

  5. Linux 下 Vi 配置文件 .vimrc 文件

    Linux 下 Vi 配置文件 .vimrc 文件 配置 vim 的方法是在用户主目录下建立个.vimrc文件,我一般使用root帐户,所以就在/root/下建立一个.vimrc文件:vi /root ...

  6. java读取resource目录下的配置文件

    java读取resource目录下的配置文件 1:配置resource目录 下的文件 host: 127.0.0.1 port: 9300 2:读取    / 代表resource目录 InputSt ...

  7. Java读取Maven工程下的配置文件,工具类

    Java开发中,经常需要在maven工程中读取src/main/resources下的配置文件: 思路如下: Class.getClassLoader() 返回类加载器ClassLoader,进而可以 ...

  8. m_Orchestrate learning system---二十九、什么情况下用数据库做配置字段,什么情况下用配置文件做配置

    m_Orchestrate learning system---二十九.什么情况下用数据库做配置字段,什么情况下用配置文件做配置 一.总结 一句话总结: 配置文件 开发人员 重置 数据库 非开发人员 ...

  9. Python获取当前路径下的配置文件

    Python获取当前路径下的配置文件 有的时候想读取当前目录下的一个配置文件.其采用的办法是: import os # 获取当前路径 curr_dir = os.path.dirname(os.pat ...

  10. Java日志组件logback使用:加载非类路径下的配置文件并设置定时更新

    Java日志组件logback使用:加载非类路径下的配置文件并设置定时更新 摘自: https://blog.csdn.net/johnson_moon/article/details/7887449 ...

随机推荐

  1. 限流中间件IpRateLimitMiddleware的使用

    前言 IpRateLimitMiddleware(Github: AspNetCoreRateLimit) 是ASPNETCore的一个限流的中间件,用于控制客户端调用API的频次, 如果客户端频繁访 ...

  2. 基于 .NET 的 Nuget 发版工具

    背景 由于 Natasha 及周边项目发版任务多,文件结构也不简单,之前一直使用基于 Github 管道脚本和 XUnit 来发版.这个方案对于发版环境与条件依赖性较强,且不够灵活,因此萌生出做一个本 ...

  3. Postgres中的Common Table Expression

    Common Table Expression 是 pg 里极为重要的特性.这个特性简单的说就是 INSERT/UPDATE/DELTE 三项操作可以返回结果集.如: update item set ...

  4. Ubuntu下安装和开启telnet

      安装命令如下 sudo apt-get install openbsd-inetd sudo apt-get install telnetd sudo /etc/init.d/openbsd-in ...

  5. Java保留两位小数的几种写法总结

    转载 本文列举了几个方法: 1. 使用java.math.BigDecimal 2. 使用java.text.DecimalFormat 3. 使用java.text.NumberFormat 4. ...

  6. Qt安卓开发经验021-030

    关于权限设置,在早期的安卓版本,所有权限都写在全局配置文件AndroidManifest.xml中,这种叫安装时权限,就是安装的时候告诉安卓系统当前app需要哪些权限.大概从安卓6开始,部分权限需要动 ...

  7. Qt编写的项目作品9-音频综合应用示例

    一.功能特点 自动计算音频振幅,绘制音频振幅曲线和音频数据曲线. 支持音频录制,可选音频输入设备.采样频率.通道等参数,Qt5默认保存wav格式,Qt6默认保存mp3格式,Qt6可选wma.aac等格 ...

  8. Qt音视频开发13-mpv录像存储

    一.前言 用mpv来做录像存储,保存视频文件,从来都没有如此的方便,直接设置属性stream-record对应的文件路径即可,我的乖乖,一行代码,如此精简美丽大方,搞得我都不敢相信自己的眼睛,mpv除 ...

  9. 编译Sophus报错: error: implicitly-declared 的参考解决方法

    一.问题描述 自己在编译Sophus时遇到如下错误: /home/wong/Datum/third_party/Sophus-1.0.0-template/Sophus-1.0.0/test/core ...

  10. [转]关于c#中遍历从数据库中取出的DataTable集合

    作为刚进入c#语言不久的小白,我们需要掌握的基本操作之DataTable集合.首先你需要一个sql语句,这里我就不写了,但是这里要注意,这个sql语句的目的是查出你需要的一张数据表,这个时候才会用到D ...