原文链接: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. vue表格轮播插件

    1.前言 需求:制作大屏看板时,经常要展示表格数据,通常一页时放不下的,表格需要自动滚动,并维持表头固定 为何自己封装:网上的滚动组件有2类,一种传入json数据进行滚动(DataV),优点是可以做到 ...

  2. 【漏洞分析】Vestra DAO 攻击事件:这个质押项目它取款不核销呀

    背景信息 攻击交易:https://app.blocksec.com/explorer/tx/eth/0x9a1d02a7cb9fef11fcec2727b1f9e0b01bc6bcf5542f5b6 ...

  3. 在CodeBolcks+wxWidgets+wxSmith下的C++编程教程——用向导创建一个wxWidgets项目(sTetris)

    0.前言 我想通过编写一个完整的游戏程序方式引导读者体验程序设计的全过程.我将采用多种方式编写具有相同效果的应用程序,并通过不同方式形成的代码和实现方法的对比来理解程序开发更深层的知识. 了解我编写教 ...

  4. 揭秘“山姆黄牛”背后的技术逻辑:用Java实现会员管理系统的防黄牛策略

    在浙江绍兴的山姆超市外,"黄牛"现象引发了广泛关注.这些"黄牛"通过提供带入和结账服务,让未办理会员卡的消费者也能进入超市购物.这一行为不仅扰乱了市场秩序,也对 ...

  5. Flutter 错误The argument type 'Color' can't be assigned to the parameter type 'MaterialStateProperty<Color?>?'.dart(argument_type_not_assignable)

    MaterialStateProperty<Color?>?和Color 当为TextButton等button添加颜色时,使用ButtonStyle为其添加颜色 TextButton( ...

  6. .NET 单文件执行程序拆解器 SingleFileExtractor

    .NET 单文件执行程序拆解器 SingleFileExtractor .NET 现在支持将程序打包为单文件格式,这方便了部署,问题是,我们不能直接看到程序中使用了哪些 DLL,更不能简单地通过查看文 ...

  7. PHP 简易的BASE64加密

    有这样一个有趣的公式:x<100;  (x*53*17)%100 = x;这个公司的原理:53*17=901,x*901,的数后2位数还是x:任何符合 a * b = 100 * n +1 的值 ...

  8. 夜莺 v8 第一个版本来了,开始做有意思的功能了

    夜莺 v8 大版本已经启动开发,预计 25 年 7.8 月份发正式版,相比 v7 大概会做四五个大功能,每个功能做完了做稳定了都会提前放出来供大家体验,虽然以 beta 来命名,实际是稳定的,大家可以 ...

  9. Qt通用方法及类库3

    函数名 //设置全局样式 static void setStyle(QUIWidget::Style style); static void setStyle(const QString &q ...

  10. Error:java: 无效的源发行版: 11

    问题描述: 昨天下载 ali 的一个 demo.本地 idea 编译的时候报错. Error:java: 无效的源发行版: 11 具体原因: 项目的 jdk (Project SDK)版本 和项目的语 ...