The first method: using MS existing ConfigurationManager to read and write
Using System.configuration;namespace zwj.tems.common{Public abstract class ConfigHelper {private Confighelp ER () {}///<summary>//Get configuration values///</summary>//<param name= "key" ;</param>//<returns></returns> public static string Getappsettingvalue (String key) {return Configurationmanager.appsettings[key]; }///<summary>///Set configuration values (existing updates, not present)///</summary>//<param name= "key" ;</param>//<param name= "value" ></param> public static void Setappsettingvalue (String ke Y, String value) {if (string. IsNullOrEmpty (Getappsettingvalue (key))) {CONFIGURATIONMANAGER.APPSETTINGS.ADD (key, value); } else {ConfigurationManager.AppSettings.Set (key, value); } Save (); ConfiGurationmanager.refreshsection ("appSettings"); }///<summary>//delete configuration values///</summary>//<param name= "key" ></param> ; public static void Removeappsetting (String key) {ConfigurationManager.AppSettings.Remove (key); Save (); Configurationmanager.refreshsection ("appSettings"); }///<summary>//Get the connection string///</summary>//<param name= "name" ></param >//<returns></returns> public static string GetConnectionString (string name) { Return Configurationmanager.connectionstrings[name]. ConnectionString; }///<summary>///Set the value of the connection string (presence is updated, not present)///</summary>//<param name= "nam E "></param>//<param name=" connstr "></param>//<param name=" provider "></pa ram> public static void SetconnEctionstring (String name,string connstr, string provider) {Connectionstringsettings connstrsettings =co Nfigurationmanager.connectionstrings[name]; New Connectionstringsettings (name, connstr, provider); if (connstrsettings! = null) {connstrsettings.connectionstring = ConnStr; Connstrsettings.providername = provider; } else {ConfigurationManager.ConnectionStrings.Add (connstrsettings); } Save (); Configurationmanager.refreshsection ("connectionStrings"); }///<summary>//Delete connection string configuration items///</summary>//<param name= "name" ></pa ram> public static void Removeconnectionstring (string name) {Configurationmanager.connections Trings. Remove (name); Save (); Configurationmanager.refreshsection ("connectionStrings"); } private static void Save () {var config = configurationmanager.openexeconfiguration (CONFIGURATIONUSERLEVEL.N one); Config. Save (configurationsavemode.modified); } }}
the second method: use native Xml+xpath to read and write (from the network)
==============================================//filename:configmanager//Description: Static method Business class for C #, ASP. NET WinForm & WebForm Program profile//app. config and the [appSettings] and [connectionStrings] nodes of Web. config for new, modified, deleted, and read related operations. ==============================================using system;using system.data;using System.Configuration;using system.web;using system.collections.generic;using system.text;using system.xml;public enum ConfigurationFile{ AppConfig = 1, webconfig = 2}///<summary>///ConfigManager application configuration File Manager///</summary>public class Configman ager{public ConfigManager () {/////TODO: Add constructor logic here//}///<summary>//For [ AppSettings] Node reads the value from the key value, returns the string///</summary>//<param name= "ConfigurationFile" > The name of the profile to be manipulated, enumeration constants & lt;/param>//<param name= "key" > key value to read </param>//<returns> string to return value values </returns> public static string Readvaluebykey (ConfigurationFile configuratioNFile, String key) {String value = String. Empty; string filename = string. Empty; if (configurationfile.tostring () = = ConfigurationFile.AppConfig.ToString ()) {filename = system.windows. Forms.Application.ExecutablePath + ". config"; } else {filename = System.AppDomain.CurrentDomain.BaseDirectory + "web. config"; } XmlDocument doc = new XmlDocument (); Doc. Load (filename); Load Config file XmlNode node = doc. selectSingleNode ("//appsettings"); Get the [appSettings] node////get [appSettings] node in relation to the key of the child node XmlElement element = (XmlElement) node. selectSingleNode ("//add[@key = '" + key + "']"); if (element! = null) {value = element. GetAttribute ("value"); } return value; }///<summary>///For [connectionStrings] node read to connectionstring value by name value, return string///</summary>//< ;p Aram Name= "ConfigurationFile" > Profile name to manipulate, enumeration constants </param><param name= "Name" > Name value to read </param>//<returns> return string for ConnectionString value </returns> pub Lic static string Readconnectionstringbyname (ConfigurationFile configurationfile, string name) {string Connecti onstring = string. Empty; string filename = string. Empty; if (configurationfile.tostring () = = ConfigurationFile.AppConfig.ToString ()) {filename = system.windows. Forms.Application.ExecutablePath + ". config"; } else {filename = System.AppDomain.CurrentDomain.BaseDirectory + "web. config"; } XmlDocument doc = new XmlDocument (); Doc. Load (filename); Load Config file XmlNode node = doc. selectSingleNode ("//connectionstrings"); Get [appSettings] node////get [connectionString] node in relation to name of child node XmlElement element = (XmlElement) node. selectSingleNode ("//add[@name = '" + name + "']"); if (element! = null) {connectionString = element. GetAttribute ("ConnectionString"); } return connectionString; }///<summary>//Update or new child node value for [appSettings] node, existing if child node is updated, new child node is not present, return success Boolean value//////</summary>// <param name= "ConfigurationFile" > Profile name to manipulate, enumeration constants </param>///<param Name= "key" > Child node Key value </param >//<param name= "value" > child node Value value </param>//<returns> return success or not Boolean </returns> public St atic bool Updateorcreateappsetting (configurationfile configurationfile, string key, String value) {bool Issucce SS = FALSE; string filename = string. Empty; if (configurationfile.tostring () = = ConfigurationFile.AppConfig.ToString ()) {filename = system.windows. Forms.Application.ExecutablePath + ". config"; } else {filename = System.AppDomain.CurrentDomain.BaseDirectory + "web. config"; } XmlDocument doc = new XmlDocument (); Doc. Load (filename); Load Config file XmlNode node = dOc. selectSingleNode ("//appsettings"); Get [appSettings] node try {////Get the child node about key in [appSettings] node XmlElement element = (xmlel ement) node. selectSingleNode ("//add[@key = '" + key + "']"); if (element! = NULL) {//Exists the child node is updated with the value element. SetAttribute ("value", value); } else {//does not exist new child node XmlElement subelement = Doc. CreateElement ("add"); Subelement.setattribute ("Key", key); Subelement.setattribute ("value", value); Node. AppendChild (subelement); }//Save to config file (mode one) using (XmlTextWriter xmlwriter = new XmlTextWriter (filename, null)) { XmlWriter. formatting = formatting.indented; Doc. WriteTo (XmlWriter); XmlWriter. Flush (); } issuccess = true; } catch (Exception ex) {IsSuccess = false; Throw ex; } return issuccess; }///<summary>//update or add the [connectionStrings] node's child node value, presence Update child node, no new child node, return success or not Boolean value/////</summary>// /<param name= "ConfigurationFile" > Profile name to manipulate, enumeration constants </param>///<param Name= "name" > child node Name value </ param>//<param name= "connectionString" > Sub-node connectionString value </param>//<param name= "Providerna Me > Child node providername value </param>//<returns> return success Boolean </returns> public static bool Updateorcreate ConnectionString (configurationfile configurationfile, string name, String ConnectionString, String providerName) { BOOL issuccess = false; string filename = string. Empty; if (configurationfile.tostring () = = ConfigurationFile.AppConfig.ToString ()) {filename = system.windows. Forms.Application.ExecutablePath + ". config"; } else {filename = System.AppDomain.CurrentDomain.BaseDirectory + "web. config"; } XmlDocument doc = new XmlDocument (); Doc. Load (filename); Load Config file XmlNode node = doc. selectSingleNode ("//connectionstrings"); Get the [connectionStrings] node try {////Get the child node about name in the [connectionStrings] node XmlElement ele ment = (XmlElement) node. selectSingleNode ("//add[@name = '" + name + "']"); if (element! = NULL) {//Exists updates the child node element. SetAttribute ("connectionString", connectionString); Element. SetAttribute ("ProviderName", providerName); } else {//does not exist new child node XmlElement subelement = Doc. CreateElement ("add"); Subelement.setattribute ("name", name); Subelement.setattribute ("connectionString", connectionString); Subelement.setattribute ("ProviderName", providerName); Node. AppendChild (subelement); }Save to config file (Mode II) Doc. Save (filename); Issuccess = true; } catch (Exception ex) {issuccess = false; Throw ex; } return issuccess; }///<summary>///delete the child nodes in the [AppSettings] node that contain the key value, and return the Boolean value of success or not//</summary>//<param name= "conf Igurationfile "> Profile name to manipulate, enumeration constants </param>//<param name=" key "> child node to delete key value </param>///<retur Ns> return success or not Boolean </returns> public static bool Deletebykey (ConfigurationFile configurationfile, string key) { BOOL issuccess = false; string filename = string. Empty; if (configurationfile.tostring () = = ConfigurationFile.AppConfig.ToString ()) {filename = system.windows. Forms.Application.ExecutablePath + ". config"; } else {filename = System.AppDomain.CurrentDomain.BaseDirectory + "web. config"; } XmlDocument doc = new XmlDocument (); Doc. Load (fIlename); Load Config file XmlNode node = doc. selectSingleNode ("//appsettings"); Get the [appSettings] node////get [appSettings] node in relation to the key of the child node XmlElement element = (XmlElement) node. selectSingleNode ("//add[@key = '" + key + "']"); if (element! = NULL) {//Exists delete child node element. Parentnode.removechild (Element); } else {//does not exist} try {//Save to config file (mode one) using (XMLTEXTWR ITER XmlWriter = new XmlTextWriter (filename, null)) {XmlWriter. formatting = formatting.indented; Doc. WriteTo (XmlWriter); XmlWriter. Flush (); } issuccess = true; } catch (Exception ex) {issuccess = false; } return issuccess; }///<summary>///delete the child nodes in the [ConnectionStrings] node that contain the name value, and return a Boolean value for success////</summary>//<param Nam E= "ConfigurationFile" > configuration file name to manipulate, enumeration constant </PARAM> <param name= "name" > child node to delete name value </param>//<returns> return success Boolean </returns> public static B Ool Deletebyname (configurationfile configurationfile, string name) {bool issuccess = false; string filename = string. Empty; if (configurationfile.tostring () = = ConfigurationFile.AppConfig.ToString ()) {filename = system.windows. Forms.Application.ExecutablePath + ". config"; } else {filename = System.AppDomain.CurrentDomain.BaseDirectory + "web. config"; } XmlDocument doc = new XmlDocument (); Doc. Load (filename); Load Config file XmlNode node = doc. selectSingleNode ("//connectionstrings"); Get [connectionStrings] node////get [connectionStrings] node in relation to name of child node XmlElement element = (XmlElement) node. selectSingleNode ("//add[@name = '" + name + "']"); if (element! = NULL) {//EXISTS Delete child nodes node. RemoveChild (Element); } else {//does not exist} try {//Save to config file (Mode II) Doc. Save (filename); Issuccess = true; } catch (Exception ex) {issuccess = false; } return issuccess; }}
More IT related technical articles and information, welcome to my personal website: http://www.zuowenjun.cn
Two scenarios for reading and writing configuration files (app. Config and web. config are common)