本文主要給大家介紹了關于ASP.NET中Config讀寫示例的相關內容,分享出來供大家參考學習,話不多說,來一起看看詳細的介紹吧。
方法如下:
如果是WinForm程序,需要添加引用:
App.config
<?xml version="1.0" encoding="utf-8" ?><configuration> <appSettings> <add key="testkey" value="0"></add> </appSettings></configuration>
NetUtilityLib
using System.Configuration;namespace pcauto{ public static class ConfigHelper { ///<summary> ///返回*.exe.config文件中appSettings配置節的value項 ///</summary> ///<param name="strKey"></param> ///<returns></returns> public static string GetAppConfig(string strKey) { string file = System.Windows.Forms.Application.ExecutablePath; Configuration config = ConfigurationManager.OpenExeConfiguration(file); foreach (string key in config.AppSettings.Settings.AllKeys) { if (key == strKey) { return config.AppSettings.Settings[strKey].Value.ToString(); } } return null; } ///<summary> ///在*.exe.config文件中appSettings配置節增加一對鍵值對 ///</summary> ///<param name="newKey"></param> ///<param name="newValue"></param> public static void UpdateAppConfig(string newKey, string newValue) { string file = System.Windows.Forms.Application.ExecutablePath; Configuration config = ConfigurationManager.OpenExeConfiguration(file); bool exist = false; foreach (string key in config.AppSettings.Settings.AllKeys) { if (key == newKey) { exist = true; } } if (exist) { config.AppSettings.Settings.Remove(newKey); } config.AppSettings.Settings.Add(newKey, newValue); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); } }}
讀示例
ConfigHelper.GetAppConfig("testkey")
寫示例
ConfigHelper.UpdateAppConfig("testkey", "abc");
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對VeVb武林網的支持
新聞熱點
疑難解答
圖片精選