C # IO stream operations,

Source: Internet
Author: User

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.

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.