At the beginning, I learned C # and wrote some simple console applications: Reading, processing, and writing files.
The concepts and usage of File, FileInfo, FileStream, and StreamReader are confusing all the time. I will summarize them today.
In summary, File, FileInfo, and FileStream are classes used for File I/O, and StreamReader is used to read and write streams from streams. before using them, you must use using System. IO.
First define a TXT document path: string txtpath = (@ "D: c0000exercise 1.txt"); read this document.
(1) File provides static methods for creating, copying, deleting, moving, and opening files, and assists in creating FileStream.
FileStream fs = File. Open (txtpath, FileMode. Open );
File can directly call various methods (Open, Delete, Exists, etc)
Example: if (File. Exists (txtpath ))
{
File. Delete (txtpath );
}
(2) FileInfo provides methods for creating, copying, deleting, moving, and opening files, and assists in creating FileStream.
FileInfo fi = new FileInfo (txtpath); // instantiate
FileStream fs = fi. Open ();
(3) FileStream supports random access to files through its Seek method. By default, FileStream opens a file in synchronous mode.
But it also supports asynchronous operations.
Using FileStream, we can get the Streams of a file and then read it.
(4) StreamReader converts characters and bytes by using Encoding to read characters from Streams.
StreamWriter converts a character to a byte by using Encoding and writes a character to Streams.
StreamReader sr = new StreamReader (fs );
String str = null;
String temp = null;
While (temp = sr. ReadLine ())! = Null)
{
Str + = "" + temp;
}
Obtain a string and then process it.
PS:
TextReader is the abstract base class of StreamReader and StringReader. The implementation of the abstract Stream class is used for byte input and output, while the implementation of TextReader is used for Unicode character output.
TextWriter is the abstract base class of StreamWriter and StringWriter. The implementation of the abstract Stream class is used for byte input and output, while the implementation of TextWriter is used for Unicode character output.