About c # stream,

Source: Internet
Author: User

About c # stream,
C # brief understanding of streamPreface

This article briefly summarizes some of the streams that are often used in C # programming. For example, simple usage of FileStream, MemoryStream, BufferedStream, NetWorkStream, StreamReader/StreamWriter, TextReader/TextWriter, etc.

 

Content

1. FileStream class

The FileStream class is mainly used to read files on the disk or write information to files on the disk. Sometimes, we need to store some data in the program to the disk or read some content in the configuration file. Here we will use this class.

Read content from files on the disk:

FileStream:

1 FileStream file = File. open (@ "F: \ file.txt", FileMode. open); // initialize the file stream 2 byte [] array = new byte [file. length]; // initialize the byte array 3 file. read (array, 0, array. length); // read the data in the stream and write it to the byte array 4 file. close (); // Close Stream 5 string str = Encoding. default. getString (array); // convert the byte array content to string 6 Console. writeLine (str );

  

Write data to a disk file:

1 1 FileStream file = File. open (@ "F: \ file.txt", FileMode. append); // initialize the file stream 2 2 byte [] array = Encoding. UTF8.GetBytes ("Hello World! Hello "); // assign 3 3 files to the byte array. write (array, 0, array. length); // write the byte array to the file stream 4 4 file. close (); // Close the streamFileStream writes files

 

 

2. MemoryStream class

MemoryStream class is mainly used to operate data in memory. For example, data transmitted over the network can be transmitted in the form of a stream. When we receive the stream data, we can declare the MemoryStream class to store and process them.

MemoryStream operation string:

1 string str = "Hi! Hello! "; 2 byte [] array = Encoding. UTF8.GetBytes (str); // converts a string to a byte array. 3. MemoryStream memory = new MemoryStream (array); // initializes the MemoryStream Class 4 byte [] arrayNew = memory. toArray (); // convert the data in the memory to a byte array 5 string strNew = Encoding. UTF8.GetString (arrayNew); // converts a byte array to a string.MemoryStream parses data

 

 

Three BufferedStream classes

The BufferedStream class is mainly used to process stream data, but its main function is to encapsulate other stream classes. Why does it mean to encapsulate other stream classes? In Microsoft's words, it is mainly to reduce the time for some streams to directly operate on storage devices. For some streams, the efficiency of directly storing data to disks is not high. For a stream packaged with BufferedStream, the data is first processed in the memory and then written into the disk, it also improves the write efficiency.

Write one file on the disk to another file on the disk:

1 1 FileStream file1 = File. open (@ "F: \ file1.txt", FileMode. openOrCreate, FileAccess. read); // Read the file stream 2 2 FileStream File 2 = file. open (@ "F: \ file2.txt", FileMode. openOrCreate, FileAccess. write); // Write the file stream 3 3 4 4 byte [] array = new byte [4096]; 5 5 6 6 BufferedStream bufferedInput = new BufferedStream (file1 ); // encapsulate the file stream 7 7 BufferedStream bufferedOutput = new BufferedStream (file2); // encapsulate the file stream 8 9 9 bufferedInput. read (array, 0, array. length); 10 10 bufferedOutput. write (array, 0, array. length); 11 11 12 12 int bytesRead = 0; 13 13 while (bytesRead = bufferedInput. read (array, 0, 4096)> 0) // Read data 14 14 {15 15 bufferedOutput. write (array, 0, bytesRead); 16 16 Console. writeLine (bytesRead); 17 17} 18 bufferedInput. close (); // Close various streams 19 19 bufferedOutput. close (); 20 20 file1.Close (); 21 21 file2.Close ();BufferedStream encapsulation stream

 

In actual tests, the efficiency of the encapsulation method is not much improved. Other streams can also encapsulate file streams. If you want to ensure that the disk is read infrequently, you only need to ensure that the Code does not do so. In fact, you can add more control on the code, and ensure that the program does not operate the disk frequently.

 

4. NetWorkStream class

NetWorkStream is a stream used to process the communication between the server and the client. It is often used in network programming. It is mainly used to process the streams obtained in classes such as Socket, TcpClient, and TcpListener.

In simple TCP synchronization mode, the Server communicates with the client:

 

1 1 TcpListener lis = new TcpListener (5000); // server listener 2 2 lis. start (); // Start 3 3 Socket sock = lis. acceptSocket (); // blocking until a client connects to 4 4 5 5 NetworkStream networkStream = new NetworkStream (sock); // obtain the Socket stream 6 6 if (netStream. dataAvailable) // if the client sends a message 7 {8 8 byte [] data = new byte [1024]; // defines a byte array, used to store received data 9 9 int len = netStream. read (data, 0, data. length); // from the position, read to the end of the byte array 10 10 string line = Encoding. default. getString (data, 0, len); // convert received bytes to string 11 11}Server

 

1 1 TcpClient client = new TcpClient (); // client tcp object 2 2 client. connect ("127.0.0.1", 5000); // Connect to Server 3 3 NetworkStream myStream = client. getStream (); // obtain the network stream 4 4 5 5 byte [] data = Encoding. default. getBytes ("Hi, hello"); // first, convert the input string message to byte 6 6 myStream. write (data, 0, data. length); // write data to myStream 7 myStream. flush (); // refresh the data in the Stream 8 myStream. close ();Client

 

5. StreamReader/StreamWriter class

StreamReader/StreamWriter is mainly used to process streaming data. They provide efficient stream reading/writing functions.

Read and Write:

1 1 StreamReader reader = new StreamReader ("filePath"); // initialize read 2 2 StreamWriter writer = new StreamWriter ("filePath "); // initialize write 3 3 4 4 4 string readStr = reader. readLine (); // read a row from the stream 5 5 string readAff = reader. readToEnd (); // read all 6 6 7 7 writer from the stream. write ("Hi"); // Write content 8 8 writer. writeLine ("Hi Hello"); // write a row 9 9 9 10 10 reader. close (); // Close stream 11 writer. close ();StreamReader/Writer

 

 

TextReader/TextWriter class

The TextReader/TextWriter class is mainly used to process streaming data. They provide efficient text stream reading/writing functions.

Read and Write:

1 1 TextReader textReader = new StringReader ("Hi"); // initialize read stream 2 2 TextWriter textWriter = new StringWriter (); // initialize the write Stream 3 3 4 4 char [] c = new char [4096]; 5 5 int chars = 0; 6 6 while (chars = textReader. read (c, 0, 4096)> 0) // write data in the stream to the character array 7 {8 8 textWriter. write (c, 0, 4096); // read stream 9 9} 10 10 11 11 string str = textWriter from the character array. toString (); // write the data in the stream to 12 12 textReader in the string. close (); // Close the stream 13 13 textWriter. close ();TextReader/Writer read/write

 

 

Note:

1. The stream must be closed after use.

2. When loading the data in the stream to the memory, consider memory overflow and other issues.

Category: C #

Related Article

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.