C # IO stream operations,
C # IO stream operations are very important. We will use this technology to read and write files. Here we will first demonstrate an example of file content replication to briefly describe IO operations in C.
Namespace ConsoleApplication1 {class Program {static void Main (string [] args) {// read the File content to Stream stream Stream = File. open ("test.txt", FileMode. openOrCreate); // initialize a byte array byte [] bytes = new byte [(int) stream. length]; // read the stream into the byte array. read (bytes, 0, bytes. length); // use MemoryStream to receive MemoryStream ms = new MemoryStream (bytes); // set ms from the beginning. seek (0, SeekOrigin. begin); // write the returned MemoryStream to another file to remove ms. writeTo (new FileStream ("newFile.txt", FileMode. openOrCreate ));}}}
Stream is an abstract class, And MemoryStream and FileStream are both subclasses of Sream.
The following example demonstrates how to asynchronously read txt text.
Namespace ConsoleApplication1 {class Program {static void Main (string [] args) {Console. writeLine (GetTxt (). result );} /// <summary> /// asynchronously read the txt text content /// </summary> /// <returns> </returns> public static async Task <string> GetTxt () {using (Stream stream = File. open ("test.txt", FileMode. openOrCreate) {using (StreamReader sr = new StreamReader (stream, Encoding. default) {return await sr. readToEndAsync ();}}}}}
For more classes and operations on IO, see https://msdn.microsoft.com/zh-cn/library/system.io (v = vs.110). aspx.