The .NET Framework provides a extensive collection of base classes in the .NET Framework which make most of the work of file handling an efficient task, with the developer needed to write only the calls to these classes.
To use the file handling classes efficiently , you may want to review the classes and their methods under the package System.IO. We will cover some of the important classes, in our use-and-study methodology through the code samples itself.
Let us see in action how the file handling is done using .NET file handling classes:
Reading a Text File
To read a text file, we will use the class StreamReader which provides an implementation of the Abstract class, TextReader and hence supports the following methods:
- Read() - Reads data from an input stream.
- ReadLine() - Reads a line of characters from the current stream and returns the data as a string.
- ReadToEnd() - Reads all characters to the end of the TextReader and returns them as one string.
Let us write a class which reads a text file and outputs its contents to the system console.
Please type the following code using your favorite text editor
using
sysyem;
using syatem.IO;
public class SampleFileReader
{
public static void main()
{
TextReader textReader = new StreanReader("samplefile.txt");
string inline = "";
while (inline = textReader.ReadLine() != null)
{
console.writeLine(inline);
}
}
}
Now Compile the program using the C# Compiler and Run the Program:
Before you run the program, create a flat file with the name "samplefile.txt" and put any text in it and save it in the same directory as the program.
Now you are ready to run the program, which will read this file and output the text to the system console:

Writing a Text File
We will use the class StreamWriter to write to a file. When we write to a file there are multiple possibilities, that the file may or may not exist, if the file is existing, we may have to specify whether the program should append to the existing file or overwrite the file.