如何用c#读写配置文件,最后一句帮了我大忙!
来源:互联网 发布:正在等待网络准备好 编辑:程序博客网 时间:2024/05/16 19:36
读配置很简单,可以用ConfigurationManager.AppSettings[key] 来读出,
可是写配置文件时,如果写成这样
ConfigurationManager.AppSettings[key] = "111";
总是提示只读,那么该怎么办呢?
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Configuration;
- namespace BQKJ.Common
- {
- /// <summary>
- /// 对exe.Config文件中的appSettings段进行读写配置操作
- /// 注意:调试时,写操作将写在vhost.exe.config文件中
- /// </summary>
- public class ConfigAppSettings
- {
- /// <summary>
- /// 写入值
- /// </summary>
- /// <param name="key"></param>
- /// <param name="value"></param>
- public static void SetValue(string key, string value)
- {
- //增加的内容写在appSettings段下 <add key="RegCode" value="0"/>
- System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
- if (config.AppSettings.Settings[key] == null)
- {
- config.AppSettings.Settings.Add(key, value);
- }
- else
- {
- config.AppSettings.Settings[key].Value = value;
- }
- config.Save(ConfigurationSaveMode.Modified);
- ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置文件
- }
- /// <summary>
- /// 读取指定key的值
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public static string GetValue(string key)
- {
- System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
- if (config.AppSettings.Settings[key] == null)
- return "";
- else
- return config.AppSettings.Settings[key].Value;
- }
- }
- }
其实也很简单,用这两个封装过的方法就可以了。
需要注意的是,在IDE调试时,写入的配置文件其实是写在了.vshost.exe.config文件中,所以你在.exe.config中是看不到的。只有直接运行exe文件时,才会正确写入到.exe.config中。
原文地址:http://www.cnblogs.com/zyj-keyen/archive/2012/07/26/2609885.html
- 如何用c#读写配置文件,最后一句帮了我大忙!
- 如何用c#读写配置文件
- 如何用c#读写配置文件
- 如何用C#读写配置文件(转载自网络)
- 如何用VFP读写配置文件(.INI)?
- Qt如何用QSettings读写ini配置文件
- 如何用c#读写配置文件(转自:http://blog.csdn.net/lanman/article/details/5287717)
- jconsole.exe帮了我的大忙
- GDB 找不到源代码【帮了我大忙】
- linux vi用法(今天帮了我大忙!!!)
- 大神的错误解释,帮了我一个大忙。
- distinct小可爱的小用法,帮了我大忙
- quartus 无法识别usb blaster确实帮了我大忙
- 小小云课堂,倒是帮了我的大忙
- 如何用JSP读写Cookie
- 如何用awk过滤最后一行的?
- 如何用C#操作注册表
- 如何用C#改文件名
- GridView自定义分页样式(上一页,下一页,到第几页)(新手教程)
- 在source insight中添加新的文件类型
- 如何判断未接来电
- Flex中采用主SWF文件加载子SWF文件中添加了Chart后,导致at mx.charts.chartClasses::ChartBase/initStyles()异常的问题解决方法
- 启动终端的办法
- 如何用c#读写配置文件,最后一句帮了我大忙!
- 权限设计思路
- SHELL命令之ln
- CF 314A(Sereja and Contest-这题题目索性没看懂,E文是硬伤)
- CentOS 6.3 yum安装LAMP(Apache+MySQL+PHP )
- 排序算法稳定性
- B. Effective Approach
- Eclipse 删除 文件所有空行
- hdwiki