Use XMLSERIALIZER to create a configuration file for ASP.NET

zhaozj2021-02-16  56

In the ASP.NET configuration file Web.config, you can easily add a custom key value pair. As follows:

The value can be taken like this. String myvalue = system.configuration.configurationSettings.Appsettings ["mykey"]; 0000-00-00 0000-00-00 0000-00-00

However, the contents of web.config are changed to the entire httpApplication, and the frequently changed data in Web.config is not suitable.

Let me introduce a method, and use the XML format to save data, the file format is as follows: Password.config

Obviously, we can add any . We can take the value through the key.

String configfile = this.mappath ("password.config"); configSetting cs = configSetting.get setting; string password = cs ["name1"];

Look at this key class Using system; use system.io; use system.Web; use system.collection; using system.xml.Serialization; use system.xml.serialization;

Namespace cjl.Web.configuration {[namespace = "http://ajliang.126.com", Typename = "configuration"] public class configSetting {setting settings; public configSetting () {}

Public string this [string key] {get {return this.Settings [key];} set {this.settings [key] = value;}} [xmlelement (elementname = "settings")] public setting settings {get {ix settings == null) {settings = new Setting ();} return settings;} set {settings = value;}} public void SaveSetting (string xmlFile) {XmlSerializer serializer = new XmlSerializer (this.GetType ()); FileStream fs = New filestream (Xmlfile, Filemode.create); streamwriter sw = new streamwriter (fs, encoding.getencoding ("gb2312"); serializer.Serialize (SW, this); sw.close ();}

public static ConfigSetting GetSetting (string xmlFile) {HttpContext context = HttpContext.Current; object s = context.Cache [xmlFile]; if (s == null) {XmlSerializer serializer = new XmlSerializer (typeof (ConfigSetting)); FileStream fs = new FileStream (XMLFile, Filemode.Open); s = serializer.deSerialize (fs); fs.close (); context.cache.insert (XMLFile, s, new cachedependency (xmlfile);}

Return (configSetting) s;}

Public class setting {add [adds; [xmlelement (elementname = "add")] public add [] add {get {return adds;} set {adds = value;}}

Public string this [string key] {get {if (adds == null) {throw new exception ("no add element");} string str = null; foreach (add add in address {if (add.key == Key) {str = add.value; break;}} {throw new Exception ("There is no elemental add" property key = " " ");} return str;} set {i (add) {add a = new add (); a.key = key; a.Value = value; adds = new add [}}; return;} foreach (add aa in address) {ix Aa.Key == key) {aa.value = value; return;}} add aaa = new add (); aaa.key = key; aaa.value = value; add [] myadds = new add [add.length 1]; adds.copyto (myadds, 0); myadds [myadds.length - 1] = aaa; adds = myadds;}} // public string this [string str]} // public class setting

Public class add {[Xmlattribute (AttributeName = "key")] public string key; [xmlattribute (attributename = "value")] public string value;}

} //

} // namespace cjl.configuration

Save, modify, add demo code to refer to WebForm1.aspx

<% @ Page language = "c #" codebehind = "Webform1.aspx.cs" autoeventwireup = "false" inherits = "testconfigsetting.webform1"%> Webform1 </ title> <meta name =" generator "content =" Microsoft Visual Studio 7.0 "> <meta name =" code_language "content =" c # "> <meta name = "vs_defaultclientscript" content = "javascript"> <meta name = "vs_targetschema" content = "http://schemas.microsoft.com/intellisense/ie5"> </ head> <body> <form id = "form1" method = "POST" runat = "server"> configfile: <ask: textBox id = "configfile" runat = "server" text = "password.config"> </ asp: textbox> <br> <ask: button id = "save "Runat =" server "text =" New A Profile "> </ asp: button> <asp: button id =" getAllKeyValueByFile "runat =" text = "display all key value pairs through the accessory file"> </ asp: button> <br> <br> Key: <asp: textbox id = "Key" runat = "server" text = "name1"> </ asp: textbox> Value: <asp: textbox id = "Value" runat = "Server" value = "mypassword"> </ asp: textbox> <br> <ask: button id = "getValuebykey" runat = "serve R "text =" Take the value by key "> </ asp: button> <asp: button id =" updateValueby "runat =" text = "by key update or add value (if there is no existing button)" > <</p> <p>/ Asp: button> <br> <br> results were as follows: <hr> <asp: label id = "Message" runat = "server"> </ asp: label> </ form> </ body> </ html> Webform1.aspx.cs</p> <p>using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls Using system.Web.ui.htmlcontrols;</p> <p>USING CJL.WEB.CONFIGURATION;</p> <p>namespace TestConfigSetting {public class WebForm1: System.Web.UI.Page {protected System.Web.UI.WebControls.TextBox Key; protected System.Web.UI.WebControls.TextBox ConfigFile; protected System.Web.UI.WebControls.Button GetAllKeyValueByFile ; protected System.Web.UI.WebControls.Button GetValueByKey; protected System.Web.UI.WebControls.Button Save; protected System.Web.UI.WebControls.TextBox Value; protected System.Web.UI.WebControls.Button UpdateValueByKey; protected System.Web.ui.WebControls.Label Message; Private Void Page_Load (Object Sender, System.EventArgs E) {// Place user code here to initialize page}</p> <p>#region Web Form Designer generated code override protected void OnInit (EventArgs e) {InitializeComponent (); base.OnInit (e);} private void InitializeComponent () {this.Save.Click = new System.EventHandler (this.Save_Click) ; this.GetAllKeyValueByFile.Click = new System.EventHandler (this.GetAllKeyValueByFile_Click); this.GetValueByKey.Click = new System.EventHandler (this.GetValueByKey_Click); this.UpdateValueByKey.Click = new System.EventHandler (this.UpdateValueByKey_Click ); This.Load = new system.eventhandler (this.page_load);</p> <p>} #Endregion</p> <p>private void GetValueByKey_Click (object sender, System.EventArgs e) {string configFile = this.MapPath (ConfigFile.Text.Trim ()); ConfigSetting cs = ConfigSetting.GetSetting (configFile); string message = ""; try {message = Key .Text.trim () "=" cs [key.text.trim ()];} catch (exception ex) {message = ex.Tostring ();} message.text = message;} private void getailKeyValueByFile_Click (Object Sender, system.eventargs e) {string configfile = this.mappath (configFile.Text.trim ()); configSetting cs = configSetting.get setting (configfile);</p> <p>String Message = ""; FOREACH (ConfigSetting.add add in cs.settings.adds) {message = add.key "=" add.value "} message.text = message;}</p> <p>Private void save_click (object sender, system.eventargs e) {string configfile = this.mappath (configfile.text.trim ()); configSetting cs = new configSetting (); cs ["name1"] = "a"; cs [ "Name2"] = "b"; cs.savesetting (configfile); message.text = "has been saved:" configfile;</p> <p>}</p> <p>private void UpdateValueByKey_Click (object sender, System.EventArgs e) {string configFile = this.MapPath (ConfigFile.Text.Trim ()); ConfigSetting cs = ConfigSetting.GetSetting (configFile); cs [Key.Text.Trim ()] = Value.Text; cs.savesetting (configfile); message.text = "Update success:" configfile;}}}</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-19337.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="19337" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.042</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'dzcuyRxwOokAUsfjGg_2BdXvUM_2F8clrhD0U0IZio4l87xg2GWaFFwH7ZxiQmOlf1rMxJ7qJ3ZjkQu_2FddAB'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>