C # && Stream

Source: Internet
Author: User

System.IO provides an abstract class stream, which supports read and write operations on bytes.

Stream is an abstract class, and all other stream classes must inherit from the Steam class. The stream class and its subclasses together form a view of the data source and data store

The stream class inherits hierarchical relationships:

The flow contains the following basic actions:

Read operation (Reading). That is, the data in the stream is read, and the data is stored in another data structure, such as an array.

Write operation (writting). That is, the data is read out from another data structure and stored in the stream object.

Search operation (seeking). The search starts from the current position in the stream and navigates to the specified location.

Because of the different data types, some streams may not support all of the above operations at the same time. For example, the network stream does not support search operations. The Stream class provides Canread,canwrite and CanSeek three properties to indicate whether the stream supports these operations.

BinaryReader and BinaryWriter

The two classes of BinaryReader and BinaryWriter provide read and write operations from string or raw data to various streams.

File and Directory

The file class supports basic operations on files, including creating, copying, moving, deleting, and opening a file.

Directory classes are used to perform common directory operations, such as creating, moving, and browsing directories and their subdirectories.

The base classes of the file class and the directory class are abstract class Filesystementry.

TextReader and TextWriter

TextReader and TextWriter classes are abstract classes. Unlike the input and output bytes in the stream class, they are used for input and output of Unicode characters.

StringReader and StringWriter

StringReader and StringWriter read characters in the string.

StreamReader and StreamWriter

StreamReader and StreamWriter read and write characters in the stream.

BufferedStream

BufferedStream is a stream type that adds buffering to a network stream, which mitigates the burden of the operating system by preventing the operating system from frequently reading data to disk.

MemoryStream

MemoryStream is a non-buffered stream that encapsulates the data directly in memory, so it can be used for fast temporary storage, inter-process message delivery, and so on.

Networksteam

Networksteam represents a stream passed on the internetwork.

Example:

Using System;
Using System.Collections.Generic;
Using System.IO;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;

Namespace ConsoleApplication9
{
Class Program
{
static void Main (string[] args)
{
byte[] buffer = NULL;

String teststring = "stream! Hello World ";
char[] Readchararray = null;
byte[] Readbuffer = null;
String readString = String. Empty;
      
using (MemoryStream stream = new MemoryStream ())
{
Console.WriteLine ("Initial string is: {0}", teststring);
If the stream is writable
if (stream. CanWrite)
{
Writes teststring to the stream
          
Buffer = Encoding.Default.GetBytes (teststring);
Write from the first position of the array with a length of 3

Stream. Write (buffer, 0, 3);

Console.WriteLine ("Now stream.postion at the {0} location", stream.) Position + 1);

Move backward 3 bits from the position you just ended (the current position) to the 7th digit
Long Newpositioninstream = stream. CanSeek? Stream. Seek (3, seekorigin.current): 0;

Console.WriteLine ("Reposition after stream.postion at {0} position", Newpositioninstream + 1);
if (Newpositioninstream < buffer. Length)
{
The new position (7th bit) has been written to the end of buffer
Stream. Write (buffer, (int) newpositioninstream, buffer. Length-(int) newpositioninstream);
}


After writing, set the stream's position property to 0 to begin reading the data in the stream
Stream. Position = 0;

Set an empty variable to receive the data in the stream, depending on the length of the stream.
Readbuffer = new Byte[stream. Length];


Sets the total number of reads for the stream,
The stream has read the data into the Readbuffer.
int count = stream. CanRead? Stream. Read (readbuffer, 0, Readbuffer.length): 0;


          

The number of the corresponding char is calculated from the Readbuffer data read out by the stream.
int charcount = Encoding.Default.GetCharCount (readbuffer, 0, Count);
Set a new Readchararray array by the number of the Char
Readchararray = new Char[charcount];

Encoding.Default.GetDecoder (). GetChars (readbuffer, 0, Count, Readchararray, 0);
for (int i = 0; i < readchararray.length; i++)
{
ReadString + = Readchararray[i];
}
Console.WriteLine ("read string: {0}", readString);
}

Stream. Close ();
}

Console.ReadLine ();

}
}
}

The results are as follows:

Example:

(1)BinaryWriter and BinaryReader

The BinaryWriter and BinaryReader classes are used to read and write data, rather than strings. Writes data to and reads data from a new, empty file stream (test.data). Once the data file has been created in the current directory, the associated BinaryWriter and Binaryreader,binarywriter are created to write the integer 0 to test.data ,test.data Place the file pointer at the end of the file. After the file pointer is set back to its initial position, BinaryReader reads the specified content.

 using system;using system.io;class mystream {Private Const string file_name = "Tes    T.data "; public static void Main (string[] args) {//Create blank file if (file.exists (file_name)) {Cons Ole.            WriteLine ("{0} already exists!", file_name);        Return        } FileStream fs = new FileStream (file_name, filemode.createnew);        Create BinaryWriter instance to write file BinaryWriter w = new BinaryWriter (FS);        Write file for (int i = 0; i < one; i++) {w.write ((int) i);        } w.close (); Fs.        Close ();        Create BinaryReader instance for read file FS = new FileStream (file_name, FileMode.Open, FileAccess.Read);        BinaryReader r = new BinaryReader (FS);        Read the file for (int i = 0; i < one; i++) {Console.WriteLine (R.readint32 ());        } r.close (); Fs.    Close (); }} 

(2) Read text from file

Using system;using system.io;class Test {public    static void Main ()     {        try         {            //Create StreamReader instance read file .                        using (StreamReader sr = new StreamReader ("TestFile.txt"))             {                String line;                Read the file to the end and show while                                (line = Sr. ReadLine ())! = null)                 {                    Console.WriteLine (line);}}        }        catch (Exception e)         {            //catch Exception            Console.WriteLine ("The file could not be read:");            Console.WriteLine (E.message);}}}    

C # && Stream

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.