C # Reading and Writing files mainly involves file, fileinfo, and filestream. They are all system. io class. streamreader is used to read and write streams from the stream. io.
First define a TXT document path: String txtpath = (@ "D: \ URL \Livebaby.cn. Txt ") to 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 an instance method 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 files synchronously, 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.
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.