C # Read XML file configuration file WinForm and Webform-demo

Source: Internet
Author: User
Tags xpath

I use the Winform and WebForm Two examples to illustrate how to manipulate an XML document for read operations as a configuration file.

1. Create a new class named "SystemConfig.cs" with the following code:

<span style= "Font-family:microsoft yahei;font-size:14px;" >using system;using system.collections.generic;using system.text;using system.xml;using System.IO;namespace        configmgrtest{public class Systemconfig {#region "basic operation Function"///<summary>//Get program working directory        </summary>//<returns></returns> private static string Getworkdirectory () {try {return Path.getdirectoryname (typeof (Systemconfig)).            Assembly.location);            } catch {return System.Windows.Forms.Application.StartupPath; }}///<summary>//Determine if string is empty string///</summary>//<param name= "Szstrin G "> Target string </param>//<returns>true: empty string; False: Non-empty string </returns> private static bool Isemptys           Tring (String szstring) {if (szstring = = null) return true; if (szstring.trim () = = string.            Empty) return true;        return false; }///<summary>///Create an XML file that formulates the root node name///</summary>//<param name= "szFileName ">xml file </param>//<param name=" szrootname "> Root node name </param>//&LT;RETURNS&GT;BOOL&LT;/R eturns> private static bool Createxmlfile (string szFileName, String szrootname) {if (Szfilena me = = NULL | |            Szfilename.trim () = = "") return false;            if (Szrootname = = NULL | | Szrootname.trim () = = "") return false;            XmlDocument Clsxmldoc = new XmlDocument ();            Clsxmldoc.appendchild (Clsxmldoc.createxmldeclaration ("1.0", "GBK", null));            Clsxmldoc.appendchild (Clsxmldoc.createnode (XmlNodeType.Element, Szrootname, ""));                try {clsxmldoc.save (szfilename);            return true;   } catch {             return false; }}///<summary>///get the corresponding XML document object from the XML file////</summary>//<param name= "Szxmlfile" >xml file </param>///<returns>xml Document Object </returns> private static XmlDocument Get            XmlDocument (String szxmlfile) {if (isemptystring (szxmlfile)) return null; if (!            File.exists (szxmlfile)) return null;            XmlDocument Clsxmldoc = new XmlDocument ();            try {clsxmldoc.load (szxmlfile);            } catch {return null;        } return Clsxmldoc; }///<summary>//Save XML Document object as XML file///</summary>//<param name= "Clsxmldoc" >xml Document Objects </param>//<param name= "Szxmlfile" >xml files </param>//<returns>bool: Saving results </returns> private static bool SavexmldocUment (XmlDocument Clsxmldoc, string szxmlfile) {if (Clsxmldoc = = null) return false;            if (isemptystring (Szxmlfile)) return false;            try {if (file.exists (szxmlfile)) File.delete (szxmlfile);            } catch {return false;            } try {Clsxmldoc.save (szxmlfile);            } catch {return false;        } return true; }///<summary>///Get the single XML node that the XPath points to//</summary>//<param name= "Clsrootno De ">xpath root node </param>//<param name=" Szxpath ">xpath expressions </param>//<returns>x            mlnode</returns> private static XmlNode Selectxmlnode (XmlNode clsrootnode, string szxpath) { if (Clsrootnode = = NULL | |        Isemptystring (Szxpath))        return null;            try {return Clsrootnode.selectsinglenode (Szxpath);            } catch {return null; }}///<summary>///Get the XML node set that the XPath points to//</summary>//<param name= "C Lsrootnode ">xpath root node </param>///<param name=" Szxpath ">xpath expression </param>//<retu        rns>xmlnodelist</returns> private static XmlNodeList Selectxmlnodes (XmlNode clsrootnode, String szxpath) {if (Clsrootnode = = NULL | |            Isemptystring (Szxpath)) return null;            try {return clsrootnode.selectnodes (Szxpath);            } catch {return null; }}///<summary>//Create a XmlNode and add to the document///</summary>//<param name= " Clsparentnode "> Parent node </param>//<param Name= "Sznodename" > Node name </param>//<returns>XmlNode</returns> private static XmlNode C Reatexmlnode (XmlNode Clsparentnode, string sznodename) {try {XmlDocument CLS                xmldoc = null;                if (Clsparentnode.gettype ()! = typeof (XmlDocument)) Clsxmldoc = clsparentnode.ownerdocument;                else Clsxmldoc = Clsparentnode as XmlDocument; XmlNode Clsxmlnode = Clsxmldoc.createnode (XmlNodeType.Element, Sznodename, String.                Empty); if (clsparentnode.gettype () = = typeof (XmlDocument)) {ClsXmlDoc.LastChild.AppendChild (cl                Sxmlnode);                } else {clsparentnode.appendchild (clsxmlnode);            } return Clsxmlnode;            } catch {return null; }}///&LT;SUMMARY&GT Sets the value of the specified attribute in the specified node///</summary>//<param name= "ParentNode" >xml node </param>//&lt ;p Aram Name= "Szattrname" > property name </param>//<param name= "Szattrvalue" > property value </param>//< returns>bool</returns> private static bool Setxmlattr (XmlNode Clsxmlnode, String szattrname, String szattr            Value) {if (Clsxmlnode = = null) return false;            if (isemptystring (Szattrname)) return false; if (isemptystring (szattrvalue)) Szattrvalue = string.            Empty;            XmlAttribute Clsattrnode = ClsXmlNode.Attributes.GetNamedItem (szattrname) as XmlAttribute;                if (Clsattrnode = = null) {XmlDocument clsxmldoc = clsxmlnode.ownerdocument;                if (Clsxmldoc = = null) return false;                Clsattrnode = Clsxmldoc.createattribute (szattrname); Clsxmlnode.attribUtes.            Append (Clsattrnode);            } clsattrnode.value = Szattrvalue;        return true;        } #endregion #region "read and write profile" private static string config_file = "Systemconfig.xml"; <summary>///Read the value of the specified key in the specified configuration file///</summary>//<param name= "Szkeyname" > read Key Name </param>///<param Name= "Szdefaultvalue" > The value returned when the specified key does not exist </param>///<returns> Key value </returns> public static int GetConfigData (string szkeyname, int ndefaultvalue) {Strin            G Szvalue = GetConfigData (Szkeyname, ndefaultvalue.tostring ()); try {return int.            Parse (Szvalue);            } catch {return ndefaultvalue; }}///<summary>///Read the value of the specified key in the specified configuration file///</summary>//<param name= "Szkeyname" > Read key name </param>//<parAm Name= "Szdefaultvalue" > The specified key does not exist, the returned value </param>//<returns>key value </returns> public sta Tic float GetConfigData (string szkeyname, float fdefaultvalue) {string szvalue = GetConfigData (Szkeynam            E, fdefaultvalue.tostring ()); try {return float.            Parse (Szvalue);            } catch {return fdefaultvalue; }}///<summary>///Read the value of the specified key in the specified configuration file///</summary>//<param name= "Szkeyname" > Read key name </param>//<param name= "Szdefaultvalue" > The value returned when the specified key does not exist </param>/        <returns>key value </returns> public static bool GetConfigData (string szkeyname, bool Bdefaultvalue)            {String szvalue = GetConfigData (Szkeyname, bdefaultvalue.tostring ()); try {return bool.            Parse (Szvalue); } catch {                return bdefaultvalue; }}///<summary>///Read the value of the specified key in the specified configuration file///</summary>//<param name= "Szkeyname" > Read key name </param>//<param name= "Szdefaultvalue" > The value returned when the specified key does not exist </param>/        <returns>key value </returns> public static string GetConfigData (String szkeyname, String szdefaultvalue) {string szconfigfile = string.            Format ("{0}\\{1}", Getworkdirectory (), config_file); if (!            File.exists (Szconfigfile)) {return szdefaultvalue;            } XmlDocument Clsxmldoc = GetXmlDocument (szconfigfile);            if (Clsxmldoc = = null) return szdefaultvalue; String Szxpath = String.            Format (".//key[@name = ' {0} ']", szkeyname);            XmlNode Clsxmlnode = Selectxmlnode (Clsxmldoc, Szxpath);          if (Clsxmlnode = = null) {return szdefaultvalue;  } XmlNode clsvalueattr = ClsXmlNode.Attributes.GetNamedItem ("value");            if (clsvalueattr = = null) return szdefaultvalue;        return clsvalueattr.value; }///<summary>///Save the value of the specified key to the specified configuration file///</summary>//<param name= "Szkeyna Me > Key name to be modified </param>//<param name= "Szvalue" > newly modified value </param> public static bool Writ Econfigdata (String szkeyname, String szvalue) {string szconfigfile = string.            Format ("{0}\\{1}", Getworkdirectory (), config_file); if (! File.exists (Szconfigfile)) {if (!            Createxmlfile (Szconfigfile, "Systemconfig")) return false;            } XmlDocument Clsxmldoc = GetXmlDocument (szconfigfile); String Szxpath = String.            Format (".//key[@name = ' {0} ']", szkeyname);            XmlNode Clsxmlnode = Selectxmlnode (Clsxmldoc, Szxpath); if (Clsxmlnode = =NULL) {Clsxmlnode = Createxmlnode (Clsxmldoc, "key"); } if (!            Setxmlattr (Clsxmlnode, "name", Szkeyname)) return false; if (!            Setxmlattr (Clsxmlnode, "value", Szvalue)) return false;        Return Savexmldocument (Clsxmldoc, szconfigfile); } #endregion}}</span>

PS: If it is WinForm, you do not have to modify the SystemConfig.cs code, if it is webform, you need to modify the following path and write and read the code, I marked the deletion of the red box,



The 2.WinForm interface is as follows:


The CS code is as follows:

<pre name= "code" class= "CSharp" ><span style= "Font-family:microsoft yahei;font-size:14px;" >using system;using system.collections.generic;using system.componentmodel;using System.Data;using System.drawing;using system.text;using system.windows.forms;namespace configmgrtest{public partial class Mainform:fo        RM {public MainForm () {InitializeComponent (); private void Btnsave_click (object sender, EventArgs e) {//Save Systemconfig .            Writeconfigdata ("UserID", This.txtUserID.Text.Trim ());            Systemconfig.writeconfigdata ("Password", This.txtPassword.Text.Trim ());            Systemconfig.writeconfigdata ("Birthday", This.textBox3.Text.Trim ());            This.txtUserID.Text = null;            This.txtPassword.Text = null;            This.textBox3.Text = null;        MessageBox.Show ("Save successfully to profile" + Application.startuppath + "systemconfig.xml \ n Click the Read button to read!"); } private void BtncloSe_click (object sender, EventArgs e) {//Read This.txtUserID.Text = Systemconfig.getconfigdata ( "UserID", String.            Empty); This.txtPassword.Text = Systemconfig.getconfigdata ("Password", String.            Empty); This.textBox3.Text = Systemconfig.getconfigdata ("Birthday", String.        Empty); }}}</span>


The 3.WebForm effect is as follows:


The front code is as follows:

<span style= "Font-family:microsoft yahei;font-size:14px;" ><%@ page language= "C #" autoeventwireup= "true" codebehind= "WebForm1.aspx.cs" inherits= "Tc.Web.WebForm1"%> <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
The background code is as follows:

<span style= "Font-family:microsoft yahei;font-size:14px;" >using system;using system.collections.generic;using system.linq;using system.web;using System.Web.UI;using        system.web.ui.webcontrols;using tc.web._code;namespace tc.web{public partial class WebForm1:System.Web.UI.Page { protected void Page_Load (object sender, EventArgs e) {} protected void Butto N2_click (object sender, EventArgs e) {//Read this. TextBox1.Text = Systemconfig.getconfigdata ("Url1", String.            Empty); This. TextBox2.Text = Systemconfig.getconfigdata ("Url2", String.                   Empty); } protected void button1_click (object sender, EventArgs e) {//write Systemconfig.writeco Nfigdata ("Url1", this.            TextBox1.Text.Trim ()); Systemconfig.writeconfigdata ("Url2", this.            TextBox2.Text.Trim ()); This.            TextBox1.Text = null; This.        TextBox2.Text = null; }}}</spaN> 

Final XML document Effects


PS: Here by the way to recommend a software, the name is called "Firstobject XML Editor" :

The Firstobject XML Editor is a feature of XML editors. The editor has a good support for Chinese, can load XML documents at high speed, and produces a customizable tree view to display the data structure of an XML document (very distinctive, none of the other XML editors), and you can call the MSXML analysis engine to verify the correctness and validity of the XML document. Its unique foal language can also be used to programmatically process XML documents, which is not typical of the XML editor.
In addition to supporting general XML editing functions, the Firstobject XML editor has special functions such as generating an XPath positioning expression for an XML node, obtaining Unicode code for the selected text, and automatically indenting and typesetting the XML code for reading. It is recommended that you try this editor for XML enthusiasts. And, this is a free software that you can always use it. :


PS: "Firstobject XML Editor" and WinForm XML read configuration file Demo:http://115.com/lb/5lbdzr1o4qf1

115 Network Tray Gift Pack code: 5LBDZR1O4QF1


C # Read XML file configuration file WinForm and Webform-demo

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.