轻量级Config文件AppSettings节点编辑帮助类
程序员文章站
2022-07-04 10:58:45
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 }