通常我們在.NET開發過程中,會接觸二種類型的設定檔:config檔案,xml檔案,下面這篇文章主要給大家介紹了關於ASP.NET中Config檔案讀寫的相關資料,文中通過範例程式碼介紹的非常詳細,需要的朋友可以參考借鑒,下面來一起看看吧。
本文主要給大家介紹了關於ASP.NET中Config讀寫樣本的相關內容,分享出來供大家參考學習,話不多說,來一起看看詳細的介紹吧。
方法如下:
如果是WinForm程式,需要添加引用:
System.ServiceModel
System.Configuration
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");