C # uses the StreamReader class and the StreamWriter class to implement file read and write operations

Source: Internet
Author: User

Read and write operations on the file should be the most important file operations, System.IO namespace for us to provide a number of file read and write operation classes, here I want to introduce the most common is the most basic StreamReader class and StreamWriter class. From the names of these two classes, it is not difficult to find that they are both stream-based read and write operations classes.

We can get a StreamReader object through the OpenText () method of the file class, through which we can implement the read operation of the text file, by the following method:

Console.WriteLine ("Reading the contents from the file");
StreamReader s = File.OpenText ("MyText.txt");
string read = null;
while ((read = S.readline ()) = null)
{
Console.WriteLine (read);
}
S.close ();
By calling the CreateText () method of the FileInfo class we can get a StreamWriter object, call WriteLine () of the StreamWriter class and we can write the data to the text file as follows:

FileInfo f = new FileInfo ("MyText.txt")
StreamWriter w = f.createtext ();
W.writeline ("This was from");
W.writeline ("Chapter 1");
W.writeline ("of C # Module");
W.write (W.newline);
W.writeline ("Thanks for your Time");
W.close ();

C # uses the StreamReader class and the StreamWriter class to implement file read and write operations

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.