Classes in the System. IO namespace provide files and other forms of input and output for hosted applications. The basic component for hosting I/o is stream, while stream is the abstract representation of byte-oriented data. Passed the System. IO. Stream class representation.
System. IO. FileStream allows access to files as streams;
System. IO. MemoryStream allows access to memory blocks as streams ;............
The most commonly used IO format for hosted and unmanaged applications is file IO. The general steps for hosting an application to read and write files are as follows:
1. Open a file with a FileStream object
2. Perform binary read/write operations. Wrap BinaryReader and BinaryWriter instances around the FileStream object, and call BinaryReader and BinaryWriter methods to execute input and output.
3. to read and write text, wrap a StreamReader and StreamWriter around the FileStream object, and then use StreamReader and StreamWriter to complete input and output.
4. Disable 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
{
If (reader! = Null)
Reader. Close ();
}
}
}
/**
* FCL is a rich class library, so there are many ways to open and read files, such
* 1. Create a FileStream with File. open and wrap a StreamReader around it
* FileStream stream = File. Open (filename, FileMode. Open, FileAccess. Read );
* StreamReader reader = new StreamReaderaa (stream );
* 2. Use File. OpenText to create a FileStream and a StreamReader in one step.
* StreamReader reader = File. OpenText (filename );
* Of course, there are other methods
* To write text, you can use StreamWriter
*/
Exception Handling is to prevent unexpected events, such as the file name of the constructor passed to StreamReader is invalid, or an exception occurs when raeder. Close () is executed.