8.1. Streams

.NET has several types of streams, each of which is derived from System.IO.Stream:

System.IO.FileStream

Provides a buffered stream used to read and write data from files.

System.IO.MemoryStream

Provides a stream that is buffered in memory instead of physical storage. This stream can alleviate the need for temporary buffers and files.

System.Net.Sockets.NetworkStream

Forward-only stream used to send and receive data through network sockets.

System.Security.Cryptography.CryptoStream

Provides a stream that associates data to cryptographic transformations.

Generally, streams support the following actions:

  • Reading using Read (synchronous) or BeginRead (asynchronous).

  • Writing using Write (synchronous) or BeginWrite (asynchronous).

  • Seeking to determine a position or change a location within the stream using Seek.

Not all streams support every action. NetworkStream, which is used to send and receive data through network sockets, does not support seeking, for example. However, it is easy to determine what capabilities a stream supports by calling CanRead, CanWrite, or CanSeek.

.NET also supports a buffered stream, which is encapsulated by the System.IO.BufferedStream class. A buffered stream contains a backing memory store that acts as a cache for read and write operations. It is most commonly used in conjunction with a NetworkStream, as data is usually read and written in chunks over a socket. The FileStream class already contains internal buffering, and memory ...

Get Object-Oriented Programming with Visual Basic .NET 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.