.NET technology FAQ (11) ----- Class library

xiaoxiao2021-03-06  61

11. Class library 11.1 file I / O11.1.1 How to read text files? First, use the System.IO.FileStream object to open the file: filestream fs = new filestream (@ "c: /test.txt", filemode.open, fileaccess.read; filestream inherits in Stream, so you can use a streamreader object FileStream object packages. This provides a good interface for a row of rows: streamreader sr = new streamreader (fs); string curline; while ((curline = sr.readline ())! = Null) Console.Writeline (curline); Turn off the StreamReader object: sr.close (); Note This will automatically call close () on the underlying Stream object, so you do not have to display fs.close (). 11.1.2 How to write a text file? Similar to the example of reading the file, just replace StreamReader to streamwriter. 11.1.3 How to read a binary? Similar to text files, just use binaryreader / write objects instead of streamreader / write to pack the filestream object. 11.1.4 How to delete a file? Use static methods to use the static method (): file.delete (@ "c: /test.txt"); 11.2 text processing 11.2.1 Support regular expressions? Yes it is. Use the System.Text.RegularExpressions.Regex class. For example, the following code updates the title of the HTML file: FileStream Fs = New FileStream ("Test.htm", FileMode.Open, FileAccess.Read; StreamReader SR = New StreamReader (fs);

Regex r = new regex (" (. *) </ Title>"); string s; while ((s = sr.readline ())! = Null) {if (R.ismatch (s)) s = R.Replace (s, "<title> new and improved $ {1} </ title>"); console.writeline (s);} 11.3 Internet11.3.1 How to download the web? First, to obtain a class using System.Net.WebRequestFactory WebRequest object: WebRequest request = WebRequestFactory.Create ( "http: // localhost"); and a request response: WebResponse response = request.GetResponse (); GetResponse method blocks until the download is complete . Then you can access your response like you: stream s = response.getResponsestream ();</p> <p>// Output the downloaded stream to the consoleStreamReader sr = new StreamReader (s); string line; while ((line = sr.ReadLine ()) = null!) Console.WriteLine (line); Note WebReponse WebRequest objects and downwardly, respectively, Compatible with HTTPWebRequest and HttpWebReponse objects, they are used to access and HTTP-related features. 11.3.2 How to use proxy servers (Proxy)? Two kinds - do so to affect all web requests: system.net.globalproxyselection.select = new defaultControlObject ("proxyName", 80); another, want to set a proxy service for a specific web request, this: proxyData proxydata = new proxyData (); proxyData.HostName = "proxyname"; proxyData.Port = 80; proxyData.OverrideSelectProxy = true; HttpWebRequest request = (HttpWebRequest) WebRequestFactory.Create ( "http: // localhost"); request.Proxy = proxyData; 11.4 XML11.4.1 Does DOM? Yes it is. Take a look at the following sample XML document: <people> <persons> Fred </ person> <persons> Bill </ person> </ people> can handle this document: XMLDocument doc = new xmlDocument (); doc.load ("Test .xml ");</p> <p>XMLNode root = doc.documentelement;</p> <p>"XMLNode PersonElement in root.childnodes) console.writeline (PersonElement.firstchild.value.tostring ()); output is: Fredbill 11.4.2 Supply SAX? Do not. As a replacement, a new XMLReader / XMLWRITER API is provided. Like SAX, it is streaming, but it uses the "PULL" model rather than the "Push" model of SAX. This is an example: XmlTextReader Reader = New XMLTextReader ("Test.xml");</p> <p>While (Reader.Read ()) {if (reader.NodeType == xmlnodetype.eray == xmlnodetype.element && reader.name == "Person") {reader.read (); // skip to the child text console.writeline (Reader.Value }} 11.4.3 Whether to support XPath? Is by XmlNavigator class (DocumentNavigator is derived from XmlNavigator): XmlDocument doc = new XmlDocument (); doc.Load ( "test.xml"); DocumentNavigator nav = new DocumentNavigator (doc); nav.MoveToDocument ();</p> <p>Nav.Select ("Descendant :: People / Person);</p> <p>While (nav.movetonextSelected ()) {nav.movetofirstchild (); console.writeline ("{0}", nav.value);} 11.5 Thread 11.5.1 Supply multi-threaded? Yes, there is a wide range of support for multithreading. The system can generate a new thread and provide a thread pool that the application can use. 11.5.2 How to generate a thread? Create an instance of the System.Threading.Thread object to pass the ThreadStart sample that will be executed in the new thread to it. For example: class mythread {public mythread (String initdata) {m_data = initdata; m_thread = new thread (new threadstart (threadmain)); m_thread.start ();}</p> <p>// threadmain () is executed on the new thread. Private void threadmain () {console.writeline (m_data);</p> <p>Public void waituntilfinished () {m_thread.join ();</p> <p>Private thread m_thread; private string m_data;} One instance of creating Mythread is enough to generate threads and execute mythread.threadmain (): mythread t = new mythread ("Hello, World."); t.waituntilfinished (); 11.5. 3 How to stop a thread? There are several ways. First, you can use your own communication mechanism to tell the threadstart method to end. In addition, the Thread class has built-in support to command the thread to stop. Basic two methods are Thread.Interrupt () and thread.abort (). The former caused a ThreadInterruptedException and then entered the WaitJointEP state. In other words, Thread.Interrupt is a polite way that requests the thread to stop when there is no useful work. Corresponding to this, thread.abort () throws a ThreadAbortexception instead of the consignment of the thread. Moreover, ThreadAbortException cannot be captured as usual (even if the THReadStart termination) is performed. Thread.abort () is a very means of unnecessary under normal circumstances. 11.5.4 How to use a thread pool? One example of the transfer by the ThreadPool.QueueUserWorkItem WaitCallback () method: class CApp {static void Main () {string s = "Hello, World"; ThreadPool.QueueUserWorkItem (new WaitCallback (DoWork), s); Thread.Sleep (1000 ); // give time for work item to be executed}</p> <p>// DOWORK IS EXECUTED ON A Thread from the thread pool. Static void DOWORK (Object State);}} 11.5.5 How do I know when my thread pool work project is completed? There is no way to ask the thread pool such information. You must place the code in the waitCallback method to issue a signal to indicate that it has been completed. The event here is also useful. 11.5.6 How to prevent concurrent access to the data? Each object has a unlocked and unlocked part of the criticism. System.Threading.monitor.Enter / Exit method is used to get and release the lock. For example, the following examples only allow one thread to simultaneously enter the method f (): Class C {public void f () {Try {Monitor.Enter (this); ...} Finally {Monitor.exit (this);}} } C # has a keyword 'lock' provides simple form of the above code: Class C {public void f () {loc (this) {...}}} Note, calling Monitor.Enter (MyObject) does not mean All access to myObject is serially connected. It means the synchronization lock that is associated with myObject and no other thread can request the lock before calling Monitor.exit (o). In other words, the following class and the class given above are functionally equivalent: Class C {public void f () {lock (m_object) {...}}</p> <p>Private m_object = new object (); 11.6 Tracking 11.6.1 Is there a built-in tracking / log support? Yes, in the system.diagnostics namespace. There are two main classes for processing tracks - Debug and Trace. They work in a similar manner-different is that the tracking in the Debug class can only work in the code generated by the Debug flag, and the tracking in the Trace class can only work in the code generated by the Trace tag. Typically, this means you should use System.Diagnostics.Trace.writeline when you want to track in debug and release versions, and use system.diagnostics.debug when you want to track it in the debug version. .Writeline. 11.6.2 Can I redirect the tracking output to a file? Yes it is. Both the Debug class and the Trace class have a listners attribute, which collects the output you generated by Debug.Writeline or Trace.writeline. By default, only one collection slot is an instance of the DEFAULTTRACELISTENER class. It sends output to Win32 OutputDebugString () function and system.diagnostics.debugger.log () method. This is useful when debugging, but if you try to track a problem from the customer site, it is more appropriate to redirect the output to a file. Fortunately, the TEXTWRITERTRACELISTENER class is provided for this purpose. Here is how TextWritertracelistener redirects the Trace output to a file: trace.listener (); filestream fs = new filestream (@ "c: /log.txt", filemode.create, fileaccess.write; trace.listener. Add (FS)); Trace.Writeline (@ "this will be writen to c: /log.txt!"); Note Use trace.listener.clear () remove the default Listener. If not do it, the output will be generated simultaneously in the file and OutputDebugString (). Under normal circumstances, you don't want this, because OutputDebugString () leads to great performance overhead. 11.6.3 Can you customize the output of tracking? Yes it is. You can write your own tracelistener export class and redirect all output to it. Here is a simple example, it exports from the TextWritrtracelistener (and then built on the write files) and add time information and thread ID: Class MyListener: TextWritRaceListener {public MyListener (Stream S): BASE (s) {}</p> <p>Public override void writeline ("{0: D8} [{1: D4}] {2}", Environment.TickCount - m_starttickcount, appdomain.getCurrentThreadId (), s);}</p> <p>Protected int m_starttickcount = environment.tickcount;}</p> <p>Pay attention to this implementation is incomplete</p> <p>-</p> <p>For example, no overlay</p> <p>TraceListener.write method.</p> <p>)</p> <p>The beauty of this method is</p> <p>Trace.Listener</p> <p>Add to</p> <p>MyListener</p> <p>After that, all pairs</p> <p>Trace.writeLine ()</p> <p>The call is turned</p> <p>MyListener</p> <p>, Including</p> <p>MyListener</p> <p>An unknown call made by the reference element.</p> <p>Microsoft</p> <p>Also released</p> <p>.NET Framework FAQ</p> <p>And this article is very similar. You can find a lot of problems here.</p> <p>"</p> <p>authority</p> <p>"</p> <p>Solution.</p> <p>Robert Scoble</p> <p>Edited an online list of easy understanding.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-119079.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="119079" 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.055</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 = 'WCCMpHbg6lJ_2BM2CE0BO6AzpD4Pv3yRUlcVI_2FwuyhB6YlhkVECTWXOl45Hlww9XnC_2BcI75UsFcbG4hEsQeAKNSA_3D_3D'; 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>