1 using System.Configuration; 2 using System.Windows.Forms; 3 4 namespace Allyn.Common 5 { 6 public class XmlHeper 7 { 8 /// 9 ///返回Config文件中appSettin... ...
1 using System.Configuration; 2 using System.Windows.Forms; 3 4 namespace Allyn.Common 5 { 6 public class XmlHeper 7 { 8 ///<summary> 9 ///返回Config文件中appSettings配置節的value項 10 ///</summary> 11 ///<param name="strKey">節點Key</param> 12 ///<returns>值</returns> 13 public static string GetAppConfig(string strKey) 14 { 15 string file = Application.ExecutablePath; 16 Configuration config = ConfigurationManager.OpenExeConfiguration(file); 17 18 foreach (string key in config.AppSettings.Settings.AllKeys) 19 { 20 if (key == strKey) 21 { 22 return config.AppSettings.Settings[strKey].Value.ToString(); 23 } 24 } 25 return string.Empty; 26 } 27 28 ///<summary> 29 ///在Config文件中appSettings配置節增加一對鍵值對 30 ///</summary> 31 ///<param name="newKey">節點名稱</param> 32 ///<param name="newValue">信值</param> 33 public static void UpdateAppConfig(string newKey, string newValue) 34 { 35 string file = System.Windows.Forms.Application.ExecutablePath; 36 Configuration config = ConfigurationManager.OpenExeConfiguration(file); 37 38 bool exist = false; 39 40 foreach (string key in config.AppSettings.Settings.AllKeys) 41 { 42 if (key == newKey) { exist = true; } 43 } 44 45 if (exist) { config.AppSettings.Settings.Remove(newKey); } 46 47 config.AppSettings.Settings.Add(newKey, newValue); 48 config.Save(ConfigurationSaveMode.Modified); 49 50 ConfigurationManager.RefreshSection("appSettings"); 51 } 52 } 53 }