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 ("
// 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:
XMLNode root = doc.documentelement;
"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");
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 ();
Nav.Select ("Descendant :: People / Person);
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 ();}
// threadmain () is executed on the new thread. Private void threadmain () {console.writeline (m_data);
Public void waituntilfinished () {m_thread.join ();
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}
// 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) {...}}
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) {}
Public override void writeline ("{0: D8} [{1: D4}] {2}", Environment.TickCount - m_starttickcount, appdomain.getCurrentThreadId (), s);}
Protected int m_starttickcount = environment.tickcount;}
Pay attention to this implementation is incomplete
-
For example, no overlay
TraceListener.write method.
)
The beauty of this method is
Trace.Listener
Add to
MyListener
After that, all pairs
Trace.writeLine ()
The call is turned
MyListener
, Including
MyListener
An unknown call made by the reference element.
Microsoft
Also released
.NET Framework FAQ
And this article is very similar. You can find a lot of problems here.
"
authority
"
Solution.
Robert Scoble
Edited an online list of easy understanding.