11.5. Choosing a Method of Opening a File or Stream for Reading and/or Writing
Problem
When you are first learning the .NET Framework—and even for some time after—the proper way to read to, write from, or otherwise interact with files can be unclear because the framework provides so many different ways of attacking this problem. How should you determine which approach fits your scenario?
Solution
Use file streams to perform various file functions. There are five basic types of built-in file stream manipulation classes that you can use in order to read and/or write to the file stream:
-
FileStream For the most fine-grained control, use
FileStreamfor file manipulation since it provides the most low-level access to the file, and, therefore, the most complex actions become available. Some of these actions are reading and writing files in both synchronous and asynchronous fashions, methods to lock and unlock part or all of a file, seek a particular position in a file, or even read the file as a stream of either characters or bytes.-
StreamReader This type is derived from the abstract base class
TextReader. TheStreamReaderclass is designed for reading character or string input from a file. This class contains methods to read single characters, blocks of characters, lines of characters, or even the whole file into a single string variable.-
StreamWriter This class derives from the
TextWriterclass. It is designed for writing character or string output to a file. This class contains methods ...