StreamReader Class () | Microsoft Official Documentation
StreamWriter Class () | Microsoft Official Documentation
1. Text reading and writing category:
TextReader/TextWriter: text reading and writing, abstract class
1. TextReader text reading, its derived class:
- StreamReader: Read characters from a byte stream in a specific encoding.
- StringReader: Read from a string.
2. TextWriter text writing, its derived class:
- StreamWriter: Write characters into a stream in a specific encoding.
- StringWriter: Writes information to a string, which is stored in the underlying StringBuilder.
- IndentedTextWriter: Provides a text writer that can indent new lines based on Tab string tags.
- HttpWriter: Provides an HttpResponse object accessed through the internal TextWriter object.
- HtmlTextWriter: Writes marker characters and text to the server control output stream. This class provides the formatting functionality used by server controls when rendering tags to clients.
2. StreamReader class, read files
1. Example:
Constructor: default encoding is UTF-8
StreamReader srAsciiFromFile = new StreamReader("C:\\Temp\\", ); StreamReader srAsciiFromStream = new StreamReader( ()("C:\\Temp\\"),);
1. Read text from file Read(), Peek()
using (StreamReader sr = new StreamReader(path)) { while (() >= 0) { ((char)()); } }
2. Call its ReadAsync() method to read the file asynchronously.
static async Task Main() { await ReadAndDisplayFilesAsync(); } static async Task ReadAndDisplayFilesAsync() { String filename = "C:\\"; Char[] buffer; using (var sr = new StreamReader(filename)) { buffer = new Char[(int)]; await (buffer, 0, (int)); } (new String(buffer)); }
3. Read a line of characters. ReadLine()
using (StreamReader sr = new StreamReader("")) { string line; // Read and display lines from the file until the end of the file is reached. while ((line = ()) != null) { (line); } }
4. Read to the end of a file in an operation. ReadToEnd()
using (StreamReader sr = new StreamReader(path)) { (()); }
3. StreamWriter class, write files
Example:
StreamWriter class allows characters and strings to be written directly to a file
//Retain the existing data of the file and open the d:\file by appending writes.using (StreamWriter sw = new StreamWriter(@"d:\", true)) //true means additional{ //Write a new string to the file and close StreamWriter ("Another File Operation Method"); }
This is what this article about C#’s reading and writing operation files using StreamReader and StreamWriter classes has been introduced. I hope it will be helpful to everyone's learning and I hope everyone will support me more.