C#配置文件之App.config和.settings


C#的Winform下的配置文件可以分为两类: 设置文件(.settings)应用程序配置文件(.config)

应用程序配置文件可以分成:App.config自定义的.config配置文件

备注:C#下的配置文件都是标准的XML文件。

1. App.config

1.1 创建

创建winform项目之后会自动生成App.config文件,如果默认没有,可以在项目上右键–新建项–应用程序配置文件,命名为App.config。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
    <appSettings>
      <add key="key1" value="hello"/>
      <add key="key2" value="world!"/>
    </appSettings>
</configuration>

其中里面的appSettings节点和子节点是后续添加的。

1.2 文件操作(增加、修改、删除、读取)

首先,项目的引用需要增加System.Configuration,并在程序文件中添加using System.Configuration;

a. 添加键为keyName、值为keyValue的项

using System.Configuration;

public void addItem(string keyName, string keyValue)
{
    //添加配置文件的项,键为keyName,值为keyValue
    Configuration config =   ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    config.AppSettings.Settings.Add(keyName, keyValue);
    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("appSettings");//刷新命名节,这样在下次检索它时将从磁盘重新读取它。
}

b. 判断键值为KeyName的项是否存在

public bool existItem(string keyName)
{
    //判断配置文件中是否存在键为keyName的项
    foreach (string key in ConfigurationManager.AppSettings)
    {
        if (key == keyName)
        {
            //存在
            return true;
        }
    }
    return false;
}

c. 获取键值为KeyName的项的值

public string valueItem(string keyName)
{
    //返回配置文件中键为keyName的项的值
    return ConfigurationManager.AppSettings[keyName];
}

d. 修改键为keyName的项的值:

public void modifyItem(string keyName, string newKeyValue)
{
    //修改配置文件中键为keyName的项的值
    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    config.AppSettings.Settings[keyName].Value = newKeyValue;
    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("appSettings");
}

e. 删除键为KeyName的项

public void removeItem(string keyName)
{
    //删除配置文件键为keyName的项
    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    config.AppSettings.Settings.Remove(keyName);
    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("appSettings");
}

备注:

  • 通过以上代码在程序中动态修改配置文件的信息后,查看App.config文件内容并未发生改变。
  • 实际上,在项目编译后,在bin/Debug文件下,除了项目的可执行文件.exe之外,还有一个配置文件.exe.config,这个才是项目中实际使用的配置文件,在程序运行中所有的更改都将被保存于此。
  • 当App.config文件发生变更并重新编译后,bin/Debug中的.exe.config文件会被App.config的内容覆盖。

2. App.config文件中自定义节点

在上一小结中,我们通过appSettings节点(由.Net预定义的配置节点)对App.config文件进行了配置,以及介绍了该节点下数据的操作。除此之外,我们可以通过两种方式来进行自定义配置文件。

2.1 第一种 使用.Net自带的几种数据类型

2.1.1 configSections和section

可以通过configSections节点下设置section节点来自定义配置文件节点,具体如下:

注:configSection节点必须是根节点configuration下的第一个子节点。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <!--以NameValue键值/对的形式返回配置节中的信息-->
    <section name="Person" type="System.Configuration.NameValueSectionHandler"/>
      
    <!--以Dictionary字典键值对的形式返回配置节中的信息-->
    <section name="Man" type="System.Configuration.DictionarySectionHandler"/>
      
    <!--基础结构。处理 .config 文件中由单个 XML 标记所表示的各配置节。-->
    <section name="Name" type="System.Configuration.SingleTagSectionHandler"/>
  </configSections>
  <!--自定义配置节点-->
  <Person>
    <add key="老大" value="刘备" />
    <add key="老二" value="关羽" />
    <add key="老三" value="张飞" />
  </Person>
  <Man>
    <add key="老大" value="曹操" />
    <add key="老二" value="典韦" />
    <add key="老三" value="郭嘉" />
  </Man>
  <!--注意是要单个节SingleTagSectionHandler才能处理,但是无论你索性有多少个也能处理-->
  <Name one="1" two="2" three="3" four="4" five="5" />
</configuration>

其中Section节点里面的name是自定义节点的名称,type是接收配置节中的信息的数据类型。第一种方式可以使用.Net自带的几种数据类型进行装载数据,如:NameValue键值对、Dictionary字典和SingleTag基础结构。

2.1.2 程序中的调用方式
using System.Collections.Specialized;
using System.Collections;



private static void getConfigs()
{
    //读取人名
    NameValueCollection nvc = (NameValueCollection)ConfigurationManager.GetSection("Person");
    foreach (string key in nvc.AllKeys)
    {
        Console.WriteLine(key + ":" + nvc[key]);
    }

    //读取男人
    IDictionary dict = (IDictionary)ConfigurationManager.GetSection("Man");
    foreach (string key in dict.Keys)
    {
        Console.WriteLine(key + ":" + dict[key]);
    }

    IDictionary dict1 = (IDictionary)ConfigurationManager.GetSection("Name");
    foreach (string key in dict1.Keys)
    {
        Console.WriteLine(key + ":" + dict1[key]);
    }
}
2.1.3 修改

后续添加

2.2 第二种 自定义的节点数据结构

参见《C#配置文件之自定义节点》

3. 自定义配置文件(Custom.config)

以上的配置文件都是在App.config中编辑操作的,当程序中存在大量的不同类型的配置项时,所有的都放在App.Config中会降低程序的可读性,为此我们需要将同类型的配置项放在自定义配置文件中进行分门别类。

具体实现:

3.1 通过App.config文件连接到自定义配置文件custom1.config

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings file="custom1.config"/>
  <!--或者 <appSettings configSource="custom1.config">-->
</configuration>

custom1.config其根目录为App.config中调用的节点标签

<appSettings>
  <add key="item1" value="first"/>
  <add key="item2" value="second"/>
</appSettings>

程序中调用

Console.WriteLine("Custom: " + ConfigurationManager.AppSettings["item1"]);

注:自定义配置文件不会像App.config一样自动复制生产.exe.config,需要将custom1.config文件的属性复制输出到目录设置为:始终复制或者如果较新则复制

在自定义section也可采用自定义配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <!--把Framework节点的数据映射到ConfigFile类中-->
    <section name="Framework" type="ConsoleApplication.ConfigFiles.ConfigFile,ConsoleApplication"/>
  </configSections>
  <!--自定义配置节点-->
  <Framework configSource="ConfigFiles\Framework.config"/>
   ...
</configuration>

Framework.config文件

<Framework>
  <Configs>
    <add key="WebHost" value="127.0.0.1" description="网站基础地址"/>
    <add key="LogTimer" value="10" description="日志定时写入的时间间隔,单位秒。"/>
  </Configs>
</Framework>

3.2 直接调用自定义配置文件custom2.config

即在应用程序中直接调用custom2.config文件,不通过App.config连接调用。

custom2.config其根目录必须为configuration

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="item1" value="AAA"/>
    <add key="item2" value="BBB"/>
  </appSettings>
</configuration>

程序中调用如下:

ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = @"custom2.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
Console.WriteLine("custom2:"+ config.AppSettings.Settings["item1"].Value);

注:同样需要将custom2.config文件的属性复制输出到目录设置为:始终复制或者如果较新则复制

4. 设置文件(.settings)

4.1 .settings文件编辑

.settings设置文件是.Net中可以进行可视化表单编辑的设置文件,其界面如下:

.settings文件中有4个属性Name,Type,Scope,Value。重点讲一下Scope属性,Scope属性有两个值:应用程序(Application)用户(User)。这两者区别,Scope值为Application时,对应的Setting在运行时不可以修改。Scope值为User时,对应的Setting在运行时可以修改

当设置完成.settings文件后,我们可以发现在App.config自动增加了一些内容,对应上图如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="PropSettingTest.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
    </sectionGroup>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="PropSettingTest.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <userSettings>
    <PropSettingTest.Properties.Settings>
      <setting name="TitleUser" serializeAs="String">
        <value>Hello User</value>
      </setting>
      <setting name="BindingText" serializeAs="String">
        <value>Hello PropBinding</value>
      </setting>
    </PropSettingTest.Properties.Settings>
  </userSettings>
  <applicationSettings>
    <PropSettingTest.Properties.Settings>
      <setting name="TitleApp" serializeAs="String">
        <value>Hello App</value>
      </setting>
    </PropSettingTest.Properties.Settings>
  </applicationSettings>
</configuration>

同样,当程序进行编译之后,.settings文件中内容会保存在.exe.config文件中

4.2 .settings在程序中调用

//读取设置内容
string usertitle = Properties.Settings.Default.TitleUser;
string apptitle = Properties.Settings.Default.TitleApp;

//修改设置内容
Properties.Settings.Default.TitleUser = "Hello User";
Properties.Settings.Default.Save();

//当你尝试修改的属性范围为应用程序Application时,会提示不存在TitleApp的报错
//Properties.Settings.Default.TitleApp = "Hello App";

备注:

  • 范围为“应用程序”的属性,读取都是从APP.CONFIG里获取,设置也可以通过手工修改App.config改变,但是在程序中无法对其进行赋值,只能读取。
  • 范围为“用户”的属性 Settings 在第一次运行时会读取App.config里的初始值;
  • 一旦调用Save方法后,Settings里“用户”范围的属性就会保存在系统里面,从此以后,读取都会从系统里保存的值里读取,手工修改App.config里的“用户”范围的属性不会影响到这些属性,除非调用Reset方法时会从新从App.config里获取“用户”范围的属性写入到系统中。

4.3 多个.settings文件

同一个工程中,可以添加多个 .settings 文件,每一个都会生成一个封装类,各对 App.config 中的一部分进行操作。

在添加.settings文件时,可以放在Properties目录下,也可以直接放在项目目录下,两者在程序中的调用会有一点区别

程序调用

//Properties目录下的.settings文件
string usertitle = Properties.Settings.Default.TitleUser;

//项目目录下的.settings文件
string title = @MySettings.Default.Title;

4.3 .settings中属性的绑定

我们可以将.settings文件中的属性直接绑定到控件的某个属性上,具体操作如下

不过观察上图,在Properties目录下的setting1.settings文件内容并未出现在选项中,也就是只有Properties/setting.settings文件和项目目录下的.settings才能够进行属性绑定操作。
s文件
string usertitle = Properties.Settings.Default.TitleUser;

//项目目录下的.settings文件
string title = @MySettings.Default.Title;


### 4.3 `.settings`中属性的绑定

我们可以将`.settings`文件中的属性直接绑定到控件的某个属性上,具体操作如下

[外链图片转存中...(img-ZNYoJxvJ-1645175234191)]

不过观察上图,在`Properties`目录下的`setting1.settings`文件内容并未出现在选项中,也就是只有`Properties/setting.settings`文件和项目目录下的`.settings`才能够进行属性绑定操作。
  • 16
    点赞
  • 79
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值