C#读写配置文件

本文详细介绍了如何使用C#语言在程序中读取和更新App.config中的配置信息,包括添加引用、代码示例以及注意事项。同时提供了配置文件的写法和保存方法,帮助开发者在运行过程中灵活调整配置。

C#读取配置文件

在程序中读取和更新App.config中的配置信息:

  

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name ="JcConn" connectionString ="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.1.60)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL)));User Id=sxeqdb;Password=sxeqdb"/>
  </connectionStrings>
  <appSettings>
    <add key="JbPath" value="D:\quickly\山西地震\地震图片"/>
  </appSettings>
</configuration>

 

1,添加引用System.Configuration;

2,添加using System.Configuration;

3,代码

<span style="font-size:14px;">string connStr = "";          </span>
<span style="font-size:14px;">ConfigurationManager.RefreshSection("AppSettings");    </span>
<span style="font-size:14px;">connStr = System.Configuration.ConfiguratonManager.AppSettings["conn"];  </span>
<span style="font-size:14px;">// 刷新应用程序配置文件的节点,这样会重新从文件读取,用于在程序运行过程中改了配置信息
ConfigurationManager.RefreshSection("AppSettings");</span>

4,key="key",key的值不区分大小写,即conn和CONN、coNN都一样可以读取到。

 

写配置文件:

// Open App.Config of executable
    Configuration config = 
        ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    // You need to remove the old settings object before you can replace it
    if (isModified)
    {
        config.AppSettings.Settings.Remove(newKey);
    }    
    // Add an Application Setting.
    config.AppSettings.Settings.Add(newKey,newValue);   
    // Save the changes in App.config file.
    config.Save(ConfigurationSaveMode.Modified);
    // Force a reload of a changed section.
    ConfigurationManager.RefreshSection("appSettings");
有坑:调试运行的时候,保存的结果在xxxx.vshost.exe.Config而不是xxxx.exe.Config(xxxx是程序名称),所以不要以为程序没写对哈。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值