C#读写app.config中的数据

来源:互联网 发布:r语言编程艺术下载。 编辑:程序博客网 时间:2024/05/17 21:31
  1. 读语句:  
  2.           String str = ConfigurationManager.AppSettings["DemoKey"];  
  3.   
  4. 写语句:  
  5.   
  6.            Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
  7.            cfa.AppSettings.Settings["DemoKey"].Value = "DemoValue";  
  8.            cfa.Save();  
  9.   
  10. 配置文件内容格式:(app.config)  
  11.   
  12. <?xml version="1.0" encoding="utf-8" ?>  
  13. <configuration>  
  14. <appSettings>  
  15.     <add key="DemoKey" value="*" />  
  16. </appSettings>  
  17. </configuration>  
  18.   
  19. System.Configuration.ConfigurationSettings.AppSettings["Key"];  
  20. 但是现在FrameWork2.0已经明确表示此属性已经过时。并建议改为ConfigurationManager或WebConfigurationManager。并且AppSettings属性是只读的,并不支持修改属性值.  
  21.   
  22. 但是要想调用ConfigurationManager必须要先在工程里添加system.configuration.dll程序集的引用。(在解决方案管理器中右键点击工程名称,在右键菜单中选择添加引用,.net TablePage下即可找到)添加引用后可以用 String str = ConfigurationManager.AppSettings["Key"]来获取对应的值了。  
  23.   
  24. 更新配置文件:  
  25. Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
  26. cfa.AppSettings.Settings.Add("key""Name") || cfa.AppSettings.Settings["BrowseDir"].Value = "name";  
  27.   
  28. 最后调用  
  29. cfa.Save();   
  30. 当前的配置文件更新成功。  
  31.   
  32.   
  33. 读写配置文件app.config   
  34. 在.Net中提供了配置文件,让我们可以很方面的处理配置信息,这个配置是XML格式的。而且.Net中已经提供了一些访问这个文件的功能。  
  35.   
  36. 1.读取配置信息  
  37. 下面是一个配置文件的具体内容:  
  38.   
  39. <?xml version="1.0" encoding="utf-8"?>  
  40. <configuration>  
  41. <appSettings>  
  42.    <add key="ConnenctionString" value="*" />  
  43.    <add key="TmpPath" value="C:/Temp" />  
  44.    </appSettings>  
  45. </configuration>  
  46.   
  47. .net提供了可以直接访问<appsettings>(注意大小写)元素的方法,在这元素中有很多的子元素,这些子元素名称都是“add”,有两个属性分别是“key”和“value”。一般情况下我们可以将自己的配置信息写在这个区域中,通过下面的方式进行访问:  
  48.   
  49. string ConString=System.Configuration.ConfigurationSettings.AppSettings["ConnenctionString"];  
  50.   
  51. 在appsettings后面的是子元素的key属性的值,例如appsettings["connenctionstring"],我们就是访问<add key="ConnenctionString" value="*" />这个子元素,它的返回值就是“*”,即value属性的值。  
  52.   
  53. 2.设置配置信息  
  54. 如果配置信息是静态的,我们可以手工配置,要注意格式。如果配置信息是动态的,就需要我们写程序来实现。在.Net中没有写配置文件的功能,我们可以使用操作XML文件的方式来操作配置文件。下面就是一个写配置文件的例子。  
  55.   
  56.          private void SaveConfig(string ConnenctionString)  
  57.          {  
  58.              XmlDocument doc=new XmlDocument();  
  59.              //获得配置文件的全路径  
  60.              string strFileName=AppDomain.CurrentDomain.BaseDirectory.ToString()+"Code.exe.config";  
  61.              doc.LOAd(strFileName);  
  62.              //找出名称为“add”的所有元素  
  63.              XmlNodeList nodes=doc.GetElementsByTagName("add");  
  64.              for(int i=0;i<nodes.Count;i++)  
  65.              {  
  66.                  //获得将当前元素的key属性  
  67.                  XmlAttribute att=nodes[i].Attributes["key"];  
  68.                  //根据元素的第一个属性来判断当前的元素是不是目标元素  
  69.                  if (att.Value=="ConnectionString")   
  70.                  {  
  71.                      //对目标元素中的第二个属性赋值  
  72.                      att=nodes[i].Attributes["value"];  
  73.                      att.Value=ConnenctionString;  
  74.                      break;  
  75.                  }  
  76.              }  
  77.              //保存上面的修改  
  78.              doc.Save(strFileName);  
  79.          }  
  80.   
  81.   
  82. VS2005中读写配置文件  
  83. VS2003中对于应用程序配置文件(app.config或者web.config)只提供了读取的功能。而在VS2005中,对于配置文件的功能有了很大的加强。在VS2005中,对于应用程序配置文件的读写一般使用Configuration,ConfigurationManager两个类。ConfigurationManager类为客户应用程序提供了一个访问的功能。使用ConfigurationManager对象执行打开配置文件的操作后,将会返回一个Configuration的对象。通过程序实现读写配置文件的代码如下所示:  
  84.   
  85. 1.创建配置文件中的配置节所对应的类。该类必须继承自ConfigurationSection  
  86.    public sealed class ConfigurationSections : ConfigurationSection  
  87.      {  
  88.          [ConfigurationProperty("filename", DefaultValue = "default.txt")]  
  89.          public string FileName  
  90.          {  
  91.              get  
  92.              {  
  93.                  return (string)this["filename"];  
  94.              }  
  95.              set  
  96.              {  
  97.                  this["filename"] = value;  
  98.              }  
  99.          }  
  100.      }  
  101.      public sealed class BusinessSpaceConfiguration : ConfigurationSection  
  102.      {  
  103.          [ConfigurationProperty("filename")]  
  104.          public string FileName  
  105.          {  
  106.              get  
  107.              {  
  108.                  return (string)this["filename"];  
  109.              }  
  110.              set  
  111.              {  
  112.                  this["filename"] = value;  
  113.              }  
  114.          }  
  115.      }  
  116.   
  117. 2.创建配置文件代码  
  118.     private static void WriteAppConfiguration()  
  119.          {  
  120.              try  
  121.              {  
  122.                  ConfigurationSections configData = new ConfigurationSections();  
  123.                  configData.FileName = "abc.txt";  
  124.                  System.Configuration.Configuration   config =   
  125.   
  126. ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
  127.                  config.Sections.Remove("ConfigurationSections");  
  128.                  config.Sections.Add("ConfigurationSections", configData);  
  129.                  config.Save();  
  130.   
  131.                  BusinessSpaceConfiguration bsconfigData = new BusinessSpaceConfiguration();  
  132.                  bsconfigData.FileName = "def.txt";  
  133.                  System.Configuration.Configuration config1 =   
  134.   
  135. ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
  136.                  config1.Sections.Remove("BusinessSpaceConfiguration");  
  137.                  config1.Sections.Add("BusinessSpaceConfiguration", bsconfigData);  
  138.                  config1.Save();                        
  139.              }  
  140.              catch (Exception err)  
  141.              {  
  142.                  Console.Write(err.Message);  
  143.              }  
  144.          }  
  145.   
  146. 3.生成的配置文件格式如下所示:  
  147. <?xml version="1.0" encoding="utf-8"?>  
  148. <configuration>  
  149.      <configSections>  
  150.          <section   
  151.   
  152. type="ConsoleApplication1.BusinessSpaceConfiguration, ConsoleApplication1, Version=1.0.0.0,   
  153.   
  154. Culture=neutral, PublicKeyToken=null" />  
  155.          <section type="ConsoleApplication1.ConfigurationSections,   
  156.   
  157. ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />  
  158.      </configSections>  
  159.      <BusinessSpaceConfiguration filename="def.txt" />  
  160.      <ConfigurationSections filename="abc.txt" />  
  161. </configuration>  
  162.   
  163. 4.读取应用程序配置文件  
  164.     private static void ReadAppConfiguration()  
  165.          {  
  166.              ConfigurationSections obj1 = ConfigurationManager.GetSection("ConfigurationSections")   
  167.   
  168. as ConfigurationSections;  
  169.              BusinessSpaceConfiguration obj2 = ConfigurationManager.GetSection  
  170.   
  171. ("BusinessSpaceConfiguration"as BusinessSpaceConfiguration;  
  172.              Console.WriteLine(obj1.FileName);  
  173.              Console.WriteLine(obj2.FileName);  
  174.   
  175.          }  
  176.   
  177. 自定义应用程序配置文件(app.config)   
  178.   
  179. 1. 配置文件概述:   
  180. 应用程序配置文件是标准的 XML 文件,XML 标记和属性是区分大小写的。它是可以按需要更改的,开发人员可以使用配置文件来更改设置,而不必重编译应用程序。配置文件的根节点是configuration。我们经常访问的是appSettings,它是由.Net预定义配置节。我们经常使用的配置文件的架构是象下面的形式。先大概有个印象,通过后面的实例会有一个比较清楚的认识。下面的“配置节”可以理解为进行配置一个XML的节点。  
  181.   
  182. 常见配置文件模式:  
  183.   
  184. <configuration>  
  185.          <configSections>                    //配置节声明区域,包含配置节和命名空间声明  
  186.                  <section>                   //配置节声明  
  187.              <sectionGroup>                  //定义配置节组  
  188.                  <section>                   //配置节组中的配置节声明  
  189.          <appSettings>                       //预定义配置节  
  190. <Custom element for configuration section>   //配置节设置区域  
  191.   
  192. 2.只有appSettings节的配置文件及访问方法  
  193.   
  194. 下面是一个最常见的应用程序配置文件的例子,只有appSettings节。  
  195.   
  196. <?xml version="1.0" encoding="utf-8"?>  
  197. <configuration>  
  198.      <appSettings>  
  199.          <add key="connectionstring" value="User Source=.;Password=;Initial   
  200. Catalog=test;Provider=SQLOLEDB.1;" />  
  201.          <add key="TemplatePATH" value="Template" />  
  202.      </appSettings>  
  203. </configuration>  
  204. 下面来看看这样的配置文件如何方法。  
  205.   
  206. string _connectionString=ConfigurationSettings.AppSettings["connectionstring"];  
  207.   
  208. 使用ConfigurationSettings类的静态属性AppSettings就可以直接方法配置文件中的配置信息。这个属性的类型是NameValueCollection。  
  209.   
  210. 3.自定义配置文件   
  211. 3.1 自定义配置节  
  212.   
  213. 一个用户自定义的配置节,在配置文件中分为两部分:一是在<configSections></configSections>配置节中声明配置节(上面配置文件模式中的“<section>”),另外是在<configSections></configSections >之后设置配置节(上面配置文件模式中的“<Custom element for configuration section>”),有点类似一个变量先声明,后使用一样。声明一个配置文件的语句如下:  
  214. <section " type=" "/>   
  215. <section>:声明新配置节,即可创建新配置节。  
  216.   
  217. name:自定义配置节的名称。  
  218. type:自定义配置节的类型,主要包括System.Configuration.SingleTagSectionHandler、System.Configuration.DictionarySectionHandler、System.Configuration.NameValueSectionHandler。  
  219.   
  220. 不同的type不但设置配置节的方式不一样,最后访问配置文件的操作上也有差异。下面我们就举一个配置文件的  
  221.   
  222. 例子,让它包含这三个不同的type。  
  223. <?xml version="1.0" encoding="utf-8" ?>  
  224. <configuration>  
  225.      <configSections>  
  226.          <section type="System.Configuration.SingleTagSectionHandler"/>  
  227.          <section type="System.Configuration.DictionarySectionHandler"/>  
  228.          <section type="System.Configuration.NameValueSectionHandler" />  
  229.      </configSections>  
  230.       
  231.      <Test1 setting1="Hello" setting2="World"/>  
  232.      <Test2>  
  233.          <add key="Hello" value="World" />  
  234.      </Test2>  
  235.      <Test3>  
  236.          <add key="Hello" value="World" />  
  237.      </Test3>      
  238. </configuration>  
  239.   
  240. 我们对上面的自定义配置节进行说明。在声明部分使用<section type="System.Configuration.SingleTagSectionHandler"/>声明了一个配置节它的名字叫Test1,类型为SingleTagSectionHandler。在设置配置节部分使用 <Test1 setting1="Hello" setting2="World"/>设置了一个配置节,它的第一个设置的值是Hello,第二个值是World,当然还可以有更多。其它的两个配置节和这个类似。   
  241. 下面我们看在程序中如何访问这些自定义的配置节。我们用过ConfigurationSettings类的静态方法GetConfig来获取自定义配置节的信息。  
  242.   
  243. public static object GetConfig(string sectionName);  
  244.   
  245. 下面是访问这三个配置节的代码:  
  246.   
  247.   
  248. //访问配置节Test1  
  249. IDictionary IDTest1 = (IDictionary)ConfigurationSettings.GetConfig("Test1");  
  250. string str = (string)IDTest1["setting1"] +" "+(string)IDTest1["setting2"];  
  251. MessageBox.Show(str);         //输出Hello World  
  252.   
  253. //访问配置节Test1的方法2  
  254. string[] values1=new string[IDTest1.Count];  
  255. IDTest1.Values.CopyTo(values1,0);  
  256. MessageBox.Show(values1[0]+" "+values1[1]);     //输出Hello World  
  257.   
  258. //访问配置节Test2  
  259. IDictionary IDTest2 = (IDictionary)ConfigurationSettings.GetConfig("Test2");  
  260. string[] keys=new string[IDTest2.Keys.Count];  
  261. string[] values=new string[IDTest2.Keys.Count];  
  262. IDTest2.Keys.CopyTo(keys,0);  
  263. IDTest2.Values.CopyTo(values,0);  
  264. MessageBox.Show(keys[0]+" "+values[0]);  
  265.   
  266. //访问配置节Test3  
  267. NameValueCollection nc=(NameValueCollection)ConfigurationSettings.GetConfig("Test3");  
  268. MessageBox.Show(nc.AllKeys[0].ToString()+" "+nc["Hello"]);     //输出Hello World  
  269. 通过上面的代码我们可以看出,不同的type通过GetConfig返回的类型不同,具体获得配置内容的方式也不一样。   
  270.   
  271. 配置节处理程序  
  272. 返回类型  
  273.   
  274. SingleTagSectionHandler  
  275. Systems.Collections.IDictionary  
  276.   
  277. DictionarySectionHandler  
  278. Systems.Collections.IDictionary  
  279.   
  280. NameValueSectionHandler  
  281. Systems.Collections.Specialized.NameValueCollection  
  282.   
  283.   
  284. 3.2 自定义配置节组   
  285. 配置节组是使用<sectionGroup>元素,将类似的配置节分到同一个组中。配置节组声明部分将创建配置节的包含元素,在<configSections>元素中声明配置节组,并将属于该组的节置于<sectionGroup>元素中。下面是一个包含配置节组的配置文件的例子:  
  286.   
  287. <?xml version="1.0" encoding="utf-8" ?>  
  288. <configuration>  
  289.      <configSections>  
  290.          <sectionGroup >  
  291.              <section type="System.Configuration.NameValueSectionHandler"/>  
  292.          </sectionGroup>  
  293.      </configSections>  
  294.       
  295.      <TestGroup>  
  296.          <Test>  
  297.              <add key="Hello" value="World"/>  
  298.          </Test>  
  299.      </TestGroup>  
  300. </configuration>  
  301. 下面是访问这个配置节组的代码:  
  302. NameValueCollection nc=(NameValueCollection)ConfigurationSettings.GetConfig("TestGroup/Test");  
  303. MessageBox.Show(nc.AllKeys[0].ToString()+" "+nc["Hello"]);     //输出Hello World   
  304.   
  305. 配置App.config  
  306.   
  307.   
  308. 1. 向项目添加app.config文件:  
  309.   
  310. 右击项目名称,选择“添加”→“添加新建项”,在出现的“添加新项”对话框中,选择“添加应用程序配置文件”;如果项目以前没有配置文件,则默认的文件名称为“app.config”,单击“确定”。出现在设计器视图中的app.config文件为:  
  311.   
  312. <?xmlversion="1.0"encoding="utf-8" ?>  
  313. <configuration>  
  314. </configuration>  
  315.   
  316. 在项目进行编译后,在bin/Debuge文件下,将出现两个配置文件(以本项目为例),一个名为“JxcManagement.EXE.config”,另一个名为“JxcManagement.vshost.exe.config”。第一个文件为项目实际使用的配置文件,在程序运行中所做的更改都将被保存于此;第二个文件为原代码“app.config”的同步文件,在程序运行中不会发生更改。  
  317.   
  318. 2.  connectionStrings配置节:  
  319.   
  320. 请注意:如果您的SQL版本为2005 Express版,则默认安装时SQL服务器实例名为localhost/SQLExpress,须更改以下实例中“Data Source=localhost;”一句为“Data Source=localhost/SQLExpress;”,在等于号的两边不要加上空格。  
  321.   
  322. <!--数据库连接串-->  
  323.      <connectionStrings>  
  324.          <clear />  
  325.          <addname="conJxcBook" connectionString="Data Source=localhost;Initial Catalog=jxcbook;User                                     providerName="System.Data.SqlClient" />  
  326.      </connectionStrings>  
  327.   
  328. 3. appSettings配置节:  
  329.   
  330. appSettings配置节为整个程序的配置,如果是对当前用户的配置,请使用userSettings配置节,其格式与以下配置书写要求一样。  
  331.   
  332. <!--进销存管理系统初始化需要的参数-->  
  333.      <appSettings>  
  334.          <clear />  
  335.          <addkey="userName"value="" />  
  336.          <addkey="password"value="" />  
  337.          <addkey="Department"value="" />  
  338.          <addkey="returnValue"value="" />  
  339.          <addkey="pwdPattern"value="" />  
  340.          <addkey="userPattern"value="" />  
  341. </appSettings>  
  342.   
  343. 4.读取与更新app.config  
  344.   
  345. 请注意:要使用以下的代码访问app.config文件,除添加引用System.Configuration外,还必须在项目添加对System.Configuration.dll的引用。  
  346.   
  347. 4.1 读取connectionStrings配置节  
  348.   
  349. ///<summary>  
  350. ///依据连接串名字connectionName返回数据连接字符串  
  351. ///</summary>  
  352. ///<param ></param>  
  353. ///<returns></returns>  
  354. private static string GetConnectionStringsConfig(string connectionName)  
  355. {  
  356. string connectionString =   
  357.         ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString();  
  358.     Console.WriteLine(connectionString);  
  359.     return connectionString;  
  360. }  
  361.   
  362. 4.2 更新connectionStrings配置节  
  363.   
  364. ///<summary>  
  365. ///更新连接字符串  
  366. ///</summary>  
  367. ///<param >连接字符串名称</param>  
  368. ///<param >连接字符串内容</param>  
  369. ///<param >数据提供程序名称</param>  
  370. private static void UpdateConnectionStringsConfig(string newName, string newConString, string newProviderName)  
  371. {  
  372.     bool isModified = false;    //记录该连接串是否已经存在  
  373.     //如果要更改的连接串已经存在  
  374.     if (ConfigurationManager.ConnectionStrings[newName] != null)  
  375.     {  
  376.         isModified = true;  
  377.     }  
  378.     //新建一个连接字符串实例  
  379.     ConnectionStringSettings mySettings =   
  380.         new ConnectionStringSettings(newName, newConString, newProviderName);  
  381.     // 打开可执行的配置文件*.exe.config  
  382.     Configuration config =   
  383.         ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
  384.     // 如果连接串已存在,首先删除它  
  385.     if (isModified)  
  386.     {  
  387.         config.ConnectionStrings.ConnectionStrings.Remove(newName);  
  388.     }  
  389.     // 将新的连接串添加到配置文件中.  
  390.     config.ConnectionStrings.ConnectionStrings.Add(mySettings);  
  391.     // 保存对配置文件所作的更改  
  392.     config.Save(ConfigurationSaveMode.Modified);  
  393.     // 强制重新载入配置文件的ConnectionStrings配置节  
  394.     ConfigurationManager.RefreshSection("connectionStrings");  
  395. }  
  396.   
  397. 4.3 读取appStrings配置节  
  398.   
  399. ///<summary>  
  400. ///返回*.exe.config文件中appSettings配置节的value项  
  401. ///</summary>  
  402. ///<param ></param>  
  403. ///<returns></returns>  
  404. private static string GetAppConfig(string strKey)  
  405. {  
  406.     foreach (string key in ConfigurationManager.AppSettings)  
  407.     {  
  408.         if (key == strKey)  
  409.         {  
  410.             return ConfigurationManager.AppSettings[strKey];  
  411.         }  
  412.     }  
  413.     return null;  
  414. }  
  415.   
  416. 4.4 更新connectionStrings配置节  
  417.   
  418. ///<summary>  
  419. ///在*.exe.config文件中appSettings配置节增加一对键、值对  
  420. ///</summary>  
  421. ///<param ></param>  
  422. ///<param ></param>  
  423. private static void UpdateAppConfig(string newKey, string newValue)  
  424. {  
  425.     bool isModified = false;      
  426.     foreach (string key in ConfigurationManager.AppSettings)  
  427.     {  
  428.        if(key==newKey)  
  429.         {      
  430.             isModified = true;  
  431.         }  
  432.     }  
  433.   
  434.     // Open App.Config of executable  
  435.     Configuration config =   
  436.         ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
  437.     // You need to remove the old settings object before you can replace it  
  438.     if (isModified)  
  439.     {  
  440.         config.AppSettings.Settings.Remove(newKey);  
  441.     }      
  442.     // Add an Application Setting.  
  443.     config.AppSettings.Settings.Add(newKey,newValue);     
  444.     // Save the changes in App.config file.  
  445.     config.Save(ConfigurationSaveMode.Modified);  
  446.     // Force a reload of a changed section.  
  447.     ConfigurationManager.RefreshSection("appSettings");  
原创粉丝点击