CHAPTER 20 FILE I/O AND OBJECT SERIALIZATION
The FileInfo.OpenText() Method
Another open-centric member of the FileInfo type is OpenText(). Unlike Create(), Open(), OpenRead(),
or OpenWrite(), the OpenText() method returns an instance of the StreamReader type, rather than a
FileStream type. Assuming you have a file named boot.ini on your C: drive, the following snippet gives
you access to its contents:
static void Main(string[] args)
{
// Get a StreamReader object.
FileInfo f5 = new FileInfo(@"C:\boot.ini");
using(StreamReader sreader = f5.OpenText())
{
// Use the StreamReader object...
}
}
As you will see shortly, the StreamReader type provides a way to read character data from the
underlying file.
The FileInfo.CreateText() and FileInfo.AppendText() Methods
The final two FileInfo methods of interest at this point are CreateText() and AppendText(). Both return
a StreamWriter object, as shown here:
static void Main(string[] args)
{
FileInfo f6 = new FileInfo(@"C:\Test6.txt");
using(StreamWriter swriter = f6.CreateText())
{
// Use the StreamWriter object...
}
FileInfo f7 = new FileInfo(@"C:\FinalTest.txt");
using(StreamWriter swriterAppend = f7.AppendText())
{
// Use the StreamWriter object...
}
}
As you might guess, the StreamWriter type provides a way to write character data to the underlying
file.
Working with the File Type
The File type uses several static members to provide functionality almost identical to that of the
FileInfo type. Like FileInfo, File supplies AppendText(), Create(), CreateText(), Open(), OpenRead(),
OpenWrite(), and OpenText() methods. In many cases, you can use the File and FileInfo types
interchangeably. To see this in action, you can simplify each of the previous FileStream examples by
using the File type instead, like so:
static void Main(string[] args)
766