Loading

使用ConfigurationManager类 读写配置文件

 
分类: .Net freamework 1165人阅读 评论(0) 收藏 举报

使用ConfigurationManager类 读写配置文件app.config,以下为代码:

 

[c-sharp] view plaincopy
  1. using System;  
  2. using System.Configuration;  
  3.   
  4. static class Program  
  5.     {  
  6.         static void Main()  
  7.         {  
  8.             showConfig();  
  9.             UpdateAppSettings();  
  10.             showConfig();  
  11.   
  12.             Console.ReadKey(true);  
  13.         }  
  14.   
  15.         private static void showConfig()  
  16.         {  
  17.             string  = ConfigurationManager.AppSettings["Directory"];  
  18.             Console.WriteLine("AppSetting配置节 Path key的value为:" + dir + "/n");  
  19.         }  
  20.   
  21.         /// <summary>  
  22.         /// UpdateAppSettings   
  23.         /// </summary>  
  24.         public static void UpdateAppSettings()  
  25.         {  
  26.             // Get the configuration file.   
  27.             Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
  28.             Console.WriteLine("config.FIlePath: " + config.FilePath + "/n");  
  29.             config.AppSettings.Settings["Directory"].Value = "tset";  
  30.   
  31.             // Save the configuration file.   
  32.             config.AppSettings.SectionInformation.ForceSave = true;  
  33.             config.Save(ConfigurationSaveMode.Modified);  
  34.             // Force a reload of the changed section.   
  35.             ConfigurationManager.RefreshSection("appSettings");  
  36.         }   

app.config内容:

 

 

[xhtml] view plaincopy
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <configuration>  
  3.   <appSettings>  
  4.     <add key="Directory" value="C:/Documents and Settings"/>  
  5.   </appSettings>  
  6. </configuration>  

 

 

代码结果:app.config只能作为初始化的定义,工程生成后运行程序集名称.exe 修改生成后的 程序集名称.exe.Config文件

一开始调试时看到控制结果是想要的结果,但看app.config配置文件内容没变(vs2008 F5调试模式下是修改 程序集名称.vshost.exe.config配置文件)还以为是代码有问题,网上搜,也有人碰过到此现像,原来是自己没有理解到MSDN的说明。(还是有文化差异啊)

如:      Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            Console.WriteLine("config.FIlePath: " + config.FilePath + "/n");

查看config.filePath值,即了解明白了。

 

4.0的类库: http://msdn.microsoft.com/en-us/library/ms134265(v=VS.100).aspx

 

注意:此类是.net2.0后新增。

必须要先在工程里添加system.configuration.dll程序集的引用。
(在解决方案管理器中右键点击工程名称,在右键菜单中选择添加引用,.net->组件名称->下即可找到)
添加引用后可以使用System.Configuration空间下的ConfigurationManager类.

 

引用资源:
http://www.ajaxline.com/node/258
http://www.codeproject.com/KB/cs/SystemConfiguration.aspx
http://www.cnblogs.com/interboy/archive/2007/04/22/722894.html           使用ConfigurationManager类读写web.config

posted @ 2012-04-21 11:12  青岛欧姆网络科技  阅读(527)  评论(0编辑  收藏  举报