C # Learning (eight) stream

Source: Internet
Author: User

The teacher told the story about the stream, and this learning record revolves around the stream.

First, some knowledge about file operations is introduced in C #.

Let's look at the following code:

1 //get the value of a specific string from the environment variable "SystemRoot", "SystemRoot" represents the Windows system startup directory2  stringThedirectory = Environment.getenvironmentvariable ("SystemRoot"); 3 Console.WriteLine (thedirectory);4  //get the directory string Thedirectory object dir5DirectoryInfo dir =NewDirectoryInfo (thedirectory);6  //gets the file collection of the Dir directory object7fileinfo[] Filesindir =dir. GetFiles ();8  foreach(varIteminchFilesindir)9  {Ten Console.WriteLine (item. Name); One  } A  //get a subdirectory collection of the Dir object -directoryinfo[] directories =dir. GetDirectories (); -   foreach(varIteminchdirectories) the   { - Console.WriteLine (item. Name); -}

The output is as follows

To summarize, the code above is to output the names of files and directories in the Windows system startup directory (C:\Windows) to the console.

DirectoryInfo can also pass in an address for parameter initialization, such as

1 string @" C:\test\media "; 2 DirectoryInfo dir = new DirectoryInfo (thedirectory);

This allows you to open the specified directory and then manipulate it. In addition DirectoryInfo and FileInfo these two classes also integrates many functions to provide new, copy, transfer, delete and other functions, here is not introduced.

Here's a summary of some of the streams that are often used in C # programming. For example FileStream, BufferedStream, NetworkStream, Streamreader/streamwriter and so on simple usage.

1. FileStream class

The FileStream class is primarily used to read files on disk or to write information to disk files.

Read the contents from a file on disk:

1FileStream file = File.Open (@"F:\file.txt", FileMode.Open);//initializing a file stream2 byte[] Array =New byte[File. Length];//initializing a byte array3File. Read (Array,0, array. Length);//read the data in the stream and write it into a byte array4File. Close ();//Close the stream5 stringstr = Encoding.Default.GetString (array);//Converts the contents of a byte array into a string6Console.WriteLine (str);

The output is the content of file.txt.

To write data to a disk file:

 1  FileStream file = File.Open (@ " Span style= "color: #800000;" >f:\file.txt  , Filemode.append); //  Initialize the file stream  2  byte  [] array = Encoding.UTF8.GetBytes (  " hello world!  ); //  Assigning a value to a byte array  3  file. Write (Array, 0 , array. Length); //  4  file. Close (); //  close stream  

The code above will "Hello world! "File.txt was written.

  

  

2.BufferedStream class

The BufferedStream class is primarily used to process streaming data, but the main function of this class is to encapsulate other stream classes. The point of doing this is to reduce the time that some streams directly manipulate the storage device. For some streams, it is not efficient to store data directly into the disk, with bufferedstream wrapped streams that are processed in memory and then written to disk, which can also improve the efficiency of writing.

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

1 BufferedStream Package Flow2FileStream file1 = File.Open (@"F:\file1.txt", Filemode.openorcreate,fileaccess.read);//Read file stream3FileStream file2= File.Open (@"F:\file2.txt", Filemode.openorcreate,fileaccess.write);//Write file stream4 5 byte[] Array =New byte[4096];6       7BufferedStream Bufferedinput =NewBufferedStream (FILE1);//encapsulates a file stream, reads8BufferedStream Bufferedoutput =NewBufferedStream (file2);//encapsulates a file stream, writes9 TenBufferedinput.read (Array,0, Array. Length); OneBufferedoutput.write (Array,0, Array. Length); A  - intBytesread =0; -  while(Bytesread = bufferedinput.read (Array,0,4096)) >0)//Read the data the   { -Bufferedoutput.write (Array,0, bytesread); - Console.WriteLine (bytesread); -    } +Bufferedinput.close ();//Close various streams - bufferedoutput.close (); + File1. Close (); AFile2. Close ();

Summing up the above code function is to write the contents of File1 to File2. But now we may not be using this stream, and here is just an introduction to its usage.

3.NetworkStream class

The NetworkStream class is a stream specifically designed to handle server-to-client communication. It is often used in network programming, primarily to handle streams such as sockets, TcpClient, and TcpListener.

A simple TCP synchronization server communicates with the client:

Server

1TcpListener lis=NewTcpListener ( the);//Server Monitoring2Lis. Start ();//Start3Socket Sock=lis. AcceptSocket ();//blocking until a client connects4 5NetworkStream NetworkStream =NewNetworkStream (sock);//get the stream in the socket6 if(netstream.dataavailable)//If the client sends a message7 {8    byte[] data =New byte[1024x768];//defines a byte array to hold the received data9    intLen = netstream.read (data,0, data. Length);//start from position, read to end of byte arrayTen    stringline = Encoding.Default.GetString (data,0, Len);//converts the received bytes to a string One}

Client

1TcpClient client =NewTcpClient ();//Client TCP Object2Client. Connect ("127.0.0.1", the);//connecting to a server3NetworkStream mystream = client. GetStream ();//get the network stream4                 5 byte[] data = Encoding.Default.GetBytes ("Hi , hi.");//First, convert the input string message to bytes6MyStream. Write (data,0, data. Length);//Write data to MyStream7MyStream. Flush ();//Refresh data in a stream8MyStream. Close ();

  

4.Streamreader/streamwriter class

Streamreader/streamwriter is primarily used to process streaming data. They provide efficient stream read/write capabilities, respectively.

Read and write:

1StreamReader reader =NewStreamReader ("FilePath");//Initialize read, filepath to file location2StreamWriter writer =NewStreamWriter ("FilePath");//Initialize Write3 4 stringReadstr=reader. ReadLine ();//reads a row from the stream5 stringReadaff = reader. ReadToEnd ();//read all from the stream6 7Writer. Write ("Hi");//Write Content8Writer. WriteLine ("Hi");//Write a row9 TenReader. Close ();//Close the stream OneWriter. Close ();

The above code is also read and write to the file, and more efficient.

Finally, we introduce the network flow, the sample code is as follows:

1 HttpWebRequest webRequest2= (HttpWebRequest) webrequest.create ("http://www.baidu.com/"); HTTP request3 HttpWebResponse WebResponse4=(HttpWebResponse) webrequest.getresponse ();5StreamReader StreamReader =NewStreamReader (6 WebResponse.GetResponseStream (), encoding.ascii); HTTP reply7 try//handle Network exceptions8  {9     stringOutputString =Streamreader.readtoend (); Ten Console.WriteLine (outputstring); One   } A  Catch{Console.WriteLine ("Exception reading from web page"); } -Streamreader.close (); Close the stream

The above code is the Baidu home page of the HTML code read and then output, it is relatively simple and clear.

This is the end of today's learning record and a chance to add something later.

Hope that the teacher Daniel is not hesitate to enlighten you!

  

C # Learning (eight) 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.