Two Methods for reading and writing configuration files (app. config and web. config), and app. config for reading and writing

Source: Internet
Author: User

Two Methods for reading and writing configuration files (app. config and web. config), and app. config for reading and writing

Method 1: use the existing ConfigurationManager of MS to read and write data.

Using System. configuration; namespace Zwj. TEMS. common {public abstract class ConfigHelper {private ConfigHelper () {}/// <summary> /// obtain the configuration value /// </summary> /// <param name = "key"> </param> // <returns> </returns> public static string getreceivettingvalue (string key) {return ConfigurationManager. deleetask[ key] ;}/// <summary> /// set the configuration value (if the configuration value exists, it is updated. If the configuration value does not exist, it is added) /// </summary> /// <param name = "key"> </param> /// <Param name = "value"> </param> public static void setdeleettingvalue (string key, string value) {if (string. isNullOrEmpty (getreceivettingvalue (key) {ConfigurationManager. appSettings. add (key, value);} else {ConfigurationManager. appSettings. set (key, value);} Save (); ConfigurationManager. refreshSection ("receivettings ");} /// <summary> /// Delete the configuration value /// </summary> /// <param name = "key"> </param> public s Tatic void RemoveAppSetting (string key) {ConfigurationManager. appSettings. remove (key); Save (); ConfigurationManager. refreshSection ("receivettings ");} /// <summary> /// obtain the connection string /// </summary> /// <param name = "name"> </param> /// <returns> </returns> public static string GetConnectionString (string name) {return ConfigurationManager. connectionStrings [name]. connectionString;} // <summary> // sets the connection string Value (updated if yes, and added if no) /// </summary> /// <param name = "name"> </param> /// <param name = "connstr"> </param> /// <param name = "provider"> </param> public static void SetConnectionString (string name, string connstr, string provider) {ConnectionStringSettings connStrSettings = ConfigurationManager. 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 the connection string configuration item /// </summary> /// <param name = "name"> </param> public static void RemoveConnectionString (string name) {ConfigurationManager. connectionStrings. remove (name); Save (); ConfigurationManager. refreshSection ("connectionStrings");} private static void Save () {var config = ConfigurationManager. openExeConfiguration (ConfigurationUserLevel. none); config. save (ConfigurationSaveMode. modified );}}}

Method 2: use native XML + XPATH for read/write (from the Network)

// ================================================ ==========/// FileName: configManager // Description: static method business class, used for C #, ASP. NET WinForm & WebForm project configuration file // app. config and web. config's [etettings] and [connectionStrings] nodes add, modify, delete, and read 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 ConfigManager {public ConfigManager () {// TODO: add the constructor logic here. //} // <summary> /// For the [deleetask] node, the Value is read Based on the Key Value, returns the string /// </summary> /// <param name = "configurationFile"> name of the configuration file to be operated, enumerated constant </param> /// <param name = "key"> Key Value to be read </param> /// <returns> string that returns the Value </returns> public static string ReadValueByKey (ConfigurationFile configurationFile, string key) {string value = string. empty; string filename = string. empty; if (configurationFile. toString () = ConfigurationFile. appC Onfig. toString () {filename = System. windows. forms. application. executablePath + ". config ";} else {filename = System. appDomain. currentDomain. baseDirectory + "web. config ";} XmlDocument doc = new XmlDocument (); doc. load (filename); // Load the configuration file XmlNode node = doc. selectSingleNode ("// deleetask"); // obtain the [deleetask] node // obtain the Key-related subnode XmlElement = (XmlElement) node in the [deleetask] node. selectSingleNod E ("// add [@ key = '" + key + "']"); if (element! = Null) {value = element. getAttribute ("value");} return value;} // <summary> // read the connectionString value from the [connectionStrings] Node Based on the name value, returns the string /// </summary> /// <param name = "configurationFile"> name of the configuration file to be operated, enumerated constant </param> /// <param name = "name"> name value to be read </param> /// <returns> returns the string of the connectionString value </returns> public static string ReadConnectionStringByName (ConfigurationFile configurationFile, string name) {String connectionString = 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 the configuration file XmlNode node = doc. selectS IngleNode ("// connectionStrings"); // get the [etettings] node // get the name of the subnode XmlElement = (XmlElement) node in the [connectionString] node. selectSingleNode ("// add [@ name = '" + name + "']"); if (element! = Null) {connectionString = element. getAttribute ("connectionString");} return connectionString;} // <summary> // update or add the Value of a subnode of the [deleetask] node. If yes, the Value of the subnode is updated, if the node does not exist, a new subnode is added. The return value is a Boolean value of success. /// </summary> /// <param name = "configurationFile"> the name of the configuration file to be operated, enumerated constant </param> /// <param name = "key"> subnode Key value </param> /// <param name = "value"> subnode value </param> // <returns> returns a Boolean value of success or failure </returns> public static bool UpdateOrCreateAp PSetting (ConfigurationFile configurationFile, string key, string value) {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 the configuration file XmlNode node = doc. selectSingleNode ("// deleetask"); // get the [deleetask] node try {// get the Key-related subnode XmlElement = (XmlElement) in the [deleetask] Node) node. selectSingleNode ("// add [@ key = '" + key + "']"); if (element! = Null) {// If yes, the Value element of the subnode is updated. setAttribute ("value", value);} else {// Add the sub-node XmlElement subElement = doc. createElement ("add"); subElement. setAttribute ("key", key); subElement. setAttribute ("value", value); node. appendChild (subElement);} // save it to the configuration file (method 1) using (XmlTextWriter xmlwriter = new XmlTextWriter (filename, null) {xmlwriter. formatting = Formatting. indented; doc. writeTo (xmlwriter); xml Writer. flush () ;}issuccess = true;} catch (Exception ex) {isSuccess = false; throw ex;} return isSuccess ;} /// <summary> /// update or add the value of a subnode of the [connectionStrings] node. If yes, update the subnode. If no value exists, add a subnode, boolean value of success or failure returned /// </summary> /// <param name = "configurationFile"> name of the configuration file to be operated, enumerated constant </param> /// <param name = "name"> sub-node name value </param> /// <param name = "connectionString"> connectionString value of the sub-node </param> /// <param name = "providerName"> Subnode providerName value </param> // Boolean value of <returns> success or failure returned </returns> public static bool UpdateOrCreateConnectionString (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 the configuration file XmlNode node = doc. selectSingleNode ("// connectionStrings"); // get the [connectionStrings] node try {// get the Name-related sub-node XmlElement = (XmlElement) in the [connectionStrings] Node) node. selectSingleNode ("// add [@ name = '" + name + "']"); if (element! = Null) {// If yes, the child node element is updated. setAttribute ("connectionString", connectionString); element. setAttribute ("providerName", providerName);} If else {// does not exist, add the sub-node XmlElement subElement = doc. createElement ("add"); subElement. setAttribute ("name", name); subElement. setAttribute ("connectionString", connectionString); subElement. setAttribute ("providerName", providerName); node. appendChild (subElement);} // save it to the configuration file (Method 2) doc. save (filename); isSuccess = true;} catch (Exception ex) {isSuccess = false; throw ex;} return isSuccess ;} /// <summary> /// delete a subnode that contains the Key value in the [deleetask] node, boolean value of success or failure returned /// </summary> /// <param name = "configurationFile"> name of the configuration file to be operated, enumerated constant </param> /// <param name = "key"> Key value of the subnode to be deleted </param> /// <returns> returns a Boolean value indicating whether the subnode is successful </param name = "key"> /returns> public static bool DeleteByKey (ConfigurationFile configurationFile, stri Ng 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 the configuration file XmlNode node = doc. selectSingleNode ("// Deleetask"); // obtain the [deleetask] node // obtain the Key-related sub-node XmlElement element = (XmlElement) node in the [deleetask] node. selectSingleNode ("// add [@ key = '" + key + "']"); if (element! = Null) {// Delete the child node element if it exists. parentNode. removeChild (element);} else {// does not exist} try {// save to the configuration file (method 1) using (XmlTextWriter 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 subnode that contains the name value in the [connectionStrings] node. A success is returned. Boolean value or not /// </summary> /// <param name = "configurationFile"> name of the configuration file to be operated, enumerated constant </param> /// <param name = "name"> name of the subnode to be deleted </param> /// <returns> returns a Boolean value indicating whether the subnode is successful </param name = "name"> /returns> public static bool DeleteByName (ConfigurationFile configurationFile, string name) {bool isSuccess = false; string filename = string. empty; if (configurationFile. toString () = ConfigurationFile. appConfig. toString () {filename = System. window S. forms. application. executablePath + ". config ";} else {filename = System. appDomain. currentDomain. baseDirectory + "web. config ";} XmlDocument doc = new XmlDocument (); doc. load (filename); // Load the configuration file XmlNode node = doc. selectSingleNode ("// connectionStrings"); // obtain the node of [connectionStrings] // obtain the Name-related subnode XmlElement element = (XmlElement) node of the [connectionStrings] node. selectSingleNode ("// add [@ name = '" + name + "']"); If (element! = Null) {// Delete the subnode if it exists. removeChild (element);} else {// does not exist} try {// save it to the configuration file (method 2) 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.