Chapter 16. Files and Streams

Most of the techniques I’ve shown so far in this book revolve around the information that lives in objects and variables. This kind of state is stored in a particular process’s memory, but to be useful, a program must interact with a broader world. This might happen through user interface frameworks such as the ones I’ll be discussing in Chapter 19, but there’s one particular abstraction that can be used for many kinds of interactions with the outside world: a stream.

Streams are so widely used in computing that you will no doubt already be familiar with them, and a .NET stream is much the same as in most other programming systems: it is simply a sequence of bytes.[53] That makes a stream a useful abstraction for many commonly encountered features such as a file on disk, or the body of an HTTP response. A console application uses streams to represent its input and output. If you run such a program interactively, its input stream will provide the text that the user types at the keyboard, and anything the program writes to its output stream appears on screen. A program doesn’t necessarily know what kind of input or output it has, though—you can redirect these streams with console programs. For example, the input stream might actually provide the contents of a file on disk, or it could even be the output from some other program.

Note

Not all I/O APIs are stream-based. For example, in addition to the input stream, the Console class provides a ReadKey method ...

Get Programming C# 5.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.