Simple C # text file reading and writing

xiaoxiao2021-03-06  20

The class in the system.io namespace is a managed application providing files and other forms of input output. The basic components of the hosted I / O are flow, and the abstract representation of the data that is byte oriented. The stream is expressed by the System.io.Stream class.

System.IO.FileStream allows files to be accessed as flow;

System.io.MemoryStream allows memory blocks to be accessed as a stream; ............

The most commonly used IO form of managed and unmanaged applications is the file IO. The general steps of the hosted application read and write files are as follows

1. Open the file with the FileStream object

2, carry out binary read and write operation, package BinaryReader and BinaryWriter's instances around the FileStream object, and call BinaryReader and BinaryWriter to perform the input and output.

3. To read and write text, package a StreamReader and StreamWriter around the FILESTREAM object, and then complete the input and output using the StreamReader and the StreamWriter method.

4, turn off the FileStream object.

Below is a simple text file read operation

Using system; using system.io;

Class FileTest {static void main (string "args) {string filename =" testfile.txt "; // Open the file and display its content StreamReader Reader = null; try {reader = new streamreader (filename); for (String line = Reader.readLine (); Line! = NULL; line = reader.readline ()) Console.Writeline (line);} catch (ioException e) {console.writeline (E.MESSAGE);} finally {ix (Reader! = NULL) Reader.close ();}}} / ** * FCL is a very rich class library, so there are many ways to open files and read, such as * 1. Create a FileStream with file.open, and it wraps around a StreamReader * FileStream stream = File.Open (filename, FileMode.Open, FileAccess.Read); * StreamReader reader = new StreamReaderaa (stream); * 2. use File.OpenText, create a FileStream in one step and a StreamReader * streamreader reader = file.opentext (filename); * Of course, there are other methods * To write to the text, you can use streamwriter * /

The exception handling is to prevent accidents, such as the file name that is transmitted to the constructor of StreamReader, or is executing raeder.close (); the front horses cause an exception.

转载请注明原文地址:https://www.9cbs.com/read-46997.html

New Post(0)