如何用c#读写配置文件,最后一句帮了我大忙!

本文介绍如何使用 C# 对 exe.config 文件中的 appSettings 段进行读写操作。通过封装的方法可以轻松实现配置项的修改,并解决了调试过程中配置写入 .vshost.exe.config 文件的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

读配置很简单,可以用ConfigurationManager.AppSettings[key] 来读出,

可是写配置文件时,如果写成这样

ConfigurationManager.AppSettings[key] = "111";

总是提示只读,那么该怎么办呢?

 

[c-sharp]  view plain copy print ?
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.Configuration;  
  5.   
  6. namespace BQKJ.Common  
  7. {  
  8.     /// <summary>   
  9.     /// 对exe.Config文件中的appSettings段进行读写配置操作   
  10.     /// 注意:调试时,写操作将写在vhost.exe.config文件中   
  11.     /// </summary>   
  12.     public class ConfigAppSettings  
  13.     {  
  14.         /// <summary>   
  15.         /// 写入值   
  16.         /// </summary>   
  17.         /// <param name="key"></param>   
  18.         /// <param name="value"></param>   
  19.         public static void SetValue(string key, string value)  
  20.         {  
  21.             //增加的内容写在appSettings段下 <add key="RegCode" value="0"/>   
  22.             System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
  23.             if (config.AppSettings.Settings[key] == null)  
  24.             {  
  25.                 config.AppSettings.Settings.Add(key, value);  
  26.             }  
  27.             else  
  28.             {  
  29.                 config.AppSettings.Settings[key].Value = value;  
  30.             }  
  31.             config.Save(ConfigurationSaveMode.Modified);  
  32.             ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置文件    
  33.         }  
  34.   
  35.         /// <summary>   
  36.         /// 读取指定key的值   
  37.         /// </summary>   
  38.         /// <param name="key"></param>   
  39.         /// <returns></returns>   
  40.         public static string GetValue(string key)  
  41.         {   
  42.             System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
  43.             if (config.AppSettings.Settings[key] == null)  
  44.                 return "";  
  45.             else  
  46.                 return config.AppSettings.Settings[key].Value;  
  47.         }  
  48.   
  49.     }  
  50. }  

 

 

其实也很简单,用这两个封装过的方法就可以了。

需要注意的是,在IDE调试时,写入的配置文件其实是写在了.vshost.exe.config文件中,所以你在.exe.config中是看不到的。只有直接运行exe文件时,才会正确写入到.exe.config中。

原文地址:http://www.cnblogs.com/zyj-keyen/archive/2012/07/26/2609885.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值