Chapter 10. Streams and I/O

Almost all nontrivial programs need to store and retrieve persistent data, whether in a database, on a local or remote file system, or over the network. Since this is a common need, many programming environments define an abstraction called a stream that is used to model reading and writing to/from files on disk. The .NET Framework supports this abstraction fully, and also extends it into other areas such as network I/O, buffering and in-memory operations, and cryptographic services.

This chapter introduces the built-in support for streams and I/O, explains the relationships between the abstract and concrete classes in the streams architecture, demonstrates their usage, and finally explores the filesystem-specific support. Unless otherwise stated, the types mentioned in this chapter all exist in the System, System.IO, or System.IO.IsolatedStorage namespaces.

Streams and Backing Stores

The stream is a fundamental abstraction used throughout the .NET Framework to model access to persistent data. A stream represents the flow of data coming in and out of a backing store. A backing store represents the endpoint of a stream. Although a backing store is often a file or network connection, in reality it can represent any medium capable of reading or writing raw data.

A simple example is to use a stream to read and write to a file on disk. However, streams and backing stores are not limited to disk and network I/O. A more sophisticated example is to use the cryptography ...

Get C# in a Nutshell, Second Edition 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.