. Net series: stream of system. Io

Source: Internet
Author: User

Stream definition in msdn: provides a general view of the byte sequence (provides a generic view of a sequence of bytes ). This explanation is too abstract and not easy to understand. It is easier to understand stream's literal meaning "River, water flow". stream is an abstract class, it defines some unified behaviors of things similar to "water flow", including whether the "water flow" can be pumped out (read stream content ); whether water can be injected into the "water flow" (content written into the stream), and how long the "water flow" is, how to close the "water flow", and how to inject water into the "water flow, how to extract water from the "water flow" and so on.

Common stream subclasses include:

1) byte stream stored in memory by memorystream

2) The byte stream of filestream stored in the file system

3) networkstream byte streams read and written by network devices

4) bufferedstream provides a buffer for other streams

Stream provides the read/write stream method to read content from the stream in bytes. We often use reading or writing text from byte streams. Microsoft provides the streamreader and streamwriter classes to help us read and write strings on the stream.

Next, let's take a look at how to operate stream, that is, how to read byte sequences from the stream, and how to write bytes to the stream.

1. Use the stream. Read method to read bytes from the stream, as shown in the following example:

Using system; using system. collections. generic; using system. LINQ; using system. text; using system. io; namespace usestream {class program {// example of how to read the static void main (string [] ARGs) {var bytes = new byte [] {(byte) from the stream) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5, (byte) 6, (byte) 7, (byte) 8 }; using (VAR memstream = new memorystream (bytes) {int offset = 0; int readonce = 4; do {byte [] bytetemp = new byte [readonce]; // use the read method to read bytes from the stream // The first parameter byte [] stores the content read from the stream // The second parameter is the start index stored in the byte [] Array, // The third int parameter is the maximum number of bytes read at a time // The returned value is the number of bytes read at a time. The value is smaller than or equal to the third parameter int readcn = memstream. read (bytetemp, 0, readonce); For (INT I = 0; I <readcn; I ++) {console. writeline (bytetemp [I]. tostring ();} Offset + = readcn; // when the number of actually read bytes is smaller than the set number of read bytes, it indicates that if (readcn <readonce) is at the end of the stream) break;} while (true);} console. read ();}}}

2. Use stream. beginread to read the stream content of filestream

Note: beginread has the same implementation as read in some streams, such as memorystream. In filestream and networdstream, beginread is actually an asynchronous operation.

The following sample code and comments:

Using system; using system. collections. generic; using system. LINQ; using system. text; using system. io; using system. threading; namespace usebeginread {class program {// defines the asynchronous read status class asyncstate {public filestream FS {Get; set;} public byte [] buffer {Get; set ;} public manualresetevent evthandle {Get; Set ;}} static int buffersize = 512; static void main (string [] ARGs) {string filepath = "D: \ test.txt "; // open the file stream using (VAR filestream = new filestream (filepath, filemode. open, fileaccess. read) {var buffer = new byte [buffersize]; // construct the State var asyncstate = new asyncstate {FS = filestream, buffer = buffer, evthandle = new manualresetevent (false)}; // asynchronously reads iasyncresult asyncresult = filestream. beginread (buffer, 0, buffersize, new asynccallback (asyncreadcallback), asyncstate); // blocks the current thread until the reading is complete and sends a signal asyncstate. evthandle. waitone (); console. writeline (); console. writeline ("read complete"); console. read () ;}// asynchronous read callback processing method public static void asyncreadcallback (iasyncresult asyncresult) {var asyncstate = (asyncstate) asyncresult. asyncstate; int readcn = asyncstate. FS. endread (asyncresult); // determines whether to read the content if (readcn> 0) {byte [] buffer; If (readcn = buffersize) buffer = asyncstate. buffer; else {buffer = new byte [readcn]; array. copy (asyncstate. buffer, 0, buffer, 0, readcn);} // output read content value string readcontent = encoding. utf8.getstring (buffer); console. write (readcontent);} If (readcn <buffersize) {asyncstate. evthandle. set ();} else {array. clear (asyncstate. buffer, 0, buffersize); // execute the asyncstate asynchronous read operation again. FS. beginread (asyncstate. buffer, 0, buffersize, new asynccallback (asyncreadcallback), asyncstate );}}}}

3. Use stream. Write to write a byte array to the stream.

When using the write method, you must first use the canwrite method of stream to determine whether the stream is writable. The following example defines a memorystream object and then writes a byte array to the memory stream.

Using system; using system. collections. generic; using system. LINQ; using system. text; using system. io; namespace usestreamwrite {class program {static void main (string [] ARGs) {using (var ms = new memorystream () {int COUNT = 20; vaR buffer = new byte [count]; for (INT I = 0; I <count; I ++) {buffer [I] = (byte) I ;} // set the current stream position to the starting point of the stream. seek (0, seekorigin. begin); console. writeline ("Ms position is" + MS. position); // before calling the stream write method, use canwrite to determine whether stream can be written if (MS. canwrite) {Ms. write (buffer, 0, count);} // if the data is written correctly, the stream location will be moved to the start position of the write and the number of bytes written to the console. writeline ("Ms position is" + MS. position);} console. read ();}}}

4.Asynchronous write using stream. beginwriteAsynchronous write can improve program performance, because the disk or network I/O speed is much lower than the CPU speed, asynchronous write can reduce the CPU wait time.

The following is an example of an asynchronous file write operation using filestream.

Using system; using system. collections. generic; using system. LINQ; using system. text; using system. io; using system. threading; namespace usestreambeginwrite {class program {// <summary> // The parameter encapsulation class required for asynchronous callback /// </Summary> class asyncstate {public int writecountonce {Get; set;} public int offset {Get; set;} public byte [] buffer {Get; set;} public manualresetevent waithandle {Get; set;} public filestream FS {Get; set ;}} static void main (string [] ARGs) {// prepare a 1 K byte array byte [] towritebytes = new byte [1 <10]; for (INT I = 0; I <towritebytes. length; I ++) {towritebytes [I] = (byte) (I % byte. maxvalue);} string filepath = "d :\\ test.txt"; // filestream instance using (VAR filestream = new filestream (filepath, filemode. create, fileaccess. readwrite, fileshare. read) {int offset = 0; // each time a 32-byte int writecountonce = 1 is written <5; // The status asyncstate required by the construction callback function = new asyncstate {writecountonce = writecountonce, offset = offset, buffer = towritebytes, waithandle = new manualresetevent (false), FS = filestream }; // asynchronous write operation filestream. beginwrite (towritebytes, offset, writecountonce, writecallback, State); // wait until the write is completed or the status of the continue signal is sent out due to an error. waithandle. waitone ();} console. writeline ("done"); console. read ();} /// <summary> /// callback function for asynchronous writing // </Summary> /// <Param name = "asyncresult"> write status </param> static void writecallback (iasyncresult asyncresult) {asyncstate state = (asyncstate) asyncresult. asyncstate; try {state. FS. endwrite (asyncresult);} catch (exception ex) {console. writeline ("endwrite error:" + ex. message); State. waithandle. set (); return;} console. writeline ("write to" + state. FS. position); // determine whether to write data. If (State) is asynchronously written before writing data. offset + state. writecountonce <state. buffer. length) {state. offset + = state. writecountonce; console. writeline ("Call beginwrite again"); State. FS. beginwrite (state. buffer, state. offset, state. writecountonce, writecallback, State);} else {// The completion signal state. waithandle. set ();}}}}

Related reading:. Net event series: Windows File Operations of system. Io

. Net series: stream of system. Io

System. Io memory ing file shared memory

System. Io uses pipelines for inter-process communication (using system. Io. Pipes)

System. Io series: multiple threads in the LAN use named pipes to communicate instances between processes

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.