CHAPTER 20 FILE I/O AND OBJECT SERIALIZATION
Open()
Opens a file with various read/write and sharing privileges.
OpenRead()
Creates a read-only FileStream object.
OpenText()
Creates a StreamReader object (described later) that reads from an existing text
file.
OpenWrite()
Creates a write-only FileStream object.
Note that a majority of the methods of the FileInfo class return a specific I/O-centric object (e.g.,
FileStream and StreamWriter) that allows you to begin reading and writing data to (or reading from) the
associated file in a variety of formats. You will check out these types in just a moment; however, before
you see a working example, you’ll find it helpful to examine various ways to obtain a file handle using the
FileInfo class type.
The FileInfo.Create() Method
One way you can create a file handle is to use the FileInfo.Create() method, like so:
static void Main(string[] args)
{
// Make a new file on the C drive.
FileInfo f = new FileInfo(@"C:\Test.dat");
FileStream fs = f.Create();
// Use the FileStream object...
// Close down file stream.
fs.Close();
}
Notice that the FileInfo.Create() method returns a FileStream object, which exposes synchronous
and asynchronous write/read operations to/from the underlying file (more details in a moment). Be
aware that the FileStream object returned by FileInfo.Create() grants full read/write access to all users.
Also notice that after you finish with the current FileStream object, you must ensure you close down
the handle to release the underlying unmanaged stream resources. Given that FileStream implements
IDisposable, you can use the C# using scope to allow the compiler to generate the teardown logic (see
Chapter 8 for details), like so:
static void Main(string[] args)
{
// Defining a using scope for file I/O
// types is ideal.
FileInfo f = new FileInfo(@"C:\Test.dat");
using (FileStream fs = f.Create())
{
// Use the FileStream object...
}
}
763