C# 应用程序配置文件App.Config和web.config

应用程序配置文件,对于asp.net是 web.config,对于WINFORM程序是 App.Config(ExeName.exe.config)。

配置文件,对于程序本身来说,就是基础和依据,其本质是一个xml文件。

对于配置文件的操作,从.NET 2.0 开始,就非常方便了,提供了 System [.Web] .Configuration 这个管理功能的NameSpace,要使用它,需要添加对 System.configuration.dll的引用。

 

我们以最常见的 AppSettings 小节来作为例子:

假设有如下的配置文件内容:

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <appSettings>

    <add key="y" value="this is Y"/>

  </appSettings>

</configuration>

 

一、ASP.NET

 

1.命名空间

  对于ASP.NET 程序, 使用 System.Web.Configuration.WebConfigurationManager;

2.读取

  
  System.Web.Configuration.WebConfigurationManager.AppSettings[“y”];

3.添加

需要有写权限:

  

Configuration config = WebConfigurationManager.OpenWebConfiguration(null); 

AppSettingsSection app = config.AppSettings; 

app.Settings.Add("x", "this is X"); 

config.Save(ConfigurationSaveMode.Modified);

 

4.修改

Configuration config = WebConfigurationManager.OpenWebConfiguration(null); 

AppSettingsSection app = config.AppSettings; //app.Settings.Add("x", "this is X"); 

app.Settings["x"].Value = "this is not Y"; 

config.Save(ConfigurationSaveMode.Modified);

 

5.删除

Configuration config = WebConfigurationManager.OpenWebConfiguration(null); 

AppSettingsSection app = config.AppSettings;

app.Settings.Remove("x");

config.Save(ConfigurationSaveMode.Modified);

 

.

二、WINFORM / CONSOLE

 

1.命名空间

  对于WINFORM程序,使用 System.Configuration.ConfigurationManager;

2.读取

  System.Configuration.ConfigurationManager.AppSettings[“y”];

3.添加

 

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

AppSettingsSection app = config.AppSettings; 

app.Settings.Add("x", "this is X"); 

config.Save(ConfigurationSaveMode.Modified);

 

4.修改

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

AppSettingsSection app = config.AppSettings; //app.Settings.Add("x", "this is X"); 

app.Settings["x"].Value = "this is not Y"; 

config.Save(ConfigurationSaveMode.Modified);

ConfigurationManager.RefreshSection("appSettings");// 刷新命名节,在下次检索它时将从磁盘重新读取它。记住应用程序要刷新节点

 

PS: 修改后,App.config文件的x节点没有更改,而是exe.config的配置更改,读取正常

 

 

5.删除

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

AppSettingsSection app = config.AppSettings; 

app.Settings.Remove("x"); 

config.Save(ConfigurationSaveMode.Modified);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值