程序開發中經常會用到應用程序配置文件,好處就是維護人員可以直接修改配置文件進行維護,而不用修改程序。好,切入主題。
給項目添加應用程序配置文件App.config,先在里面寫幾句:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="1" value="內容一"/>
<add key="2" value="內容二"/>
<add key="3" value="內容三"/>
</appSettings>
</configuration>
讀取內容:老寫法是System.Configuration.ConfigurationSettings.AppSettings[“1”].ToString(); 這個"1"對應里面的key。
這里推薦在引用里添加System.configuration,命名空間加入using System.Configuration;
就可以寫成 ConfigurationManager.AppSettings["key"].ToString(); 這里的key就是1、2、3啦。
添加內容:
Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); cfa.AppSettings.Settings.Add("key", "value"); //最后調用save
cfa.Save(); // 刷新命名節,在下次檢索它時將從磁盤重新讀取它。記住應用程序要刷新節點
ConfigurationManager.RefreshSection("appSettings"); MessageBox.Show("添加成功");
修改內容:
Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); cfa.AppSettings.Settings["key名稱"].Value = "要改成的value值"; cfa.Save(); ConfigurationManager.RefreshSection("appSettings");
刪除內容:
cfa.AppSettings.Settings.Remove("要刪除的key名"); cfa.Save();
簡單的幾個操作就是這些,往大牛們多指教^_^