TOC

The community is working on translating this tutorial into Indonesian, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Data Streams:

Introduction

In the .NET framework, the concept of Streams are used whenever you want to read and/or write data from and to a wide range of sources/destinations, e.g. in-memory, a file, over a network connection or basically any other situation where you want to transfer bytes from one place to another.

When working with many of the IO-related classes in the .NET framework, you will see them having methods which accept a parameter of the type Stream. Stream is the base class for dealing with strings and it can take many forms, e.g. a MemoryStream or a FileStream, as we'll see in the next articles. However, the Stream class itself is abstract, which means that you can't instantiate it - it only serves as a common base class for the various types of streams.

Most Stream types can do three things: Read, Write and Seek (move to a new place in the stream, to either read or write from there instead of the current position). Therefore the Stream class implements three methods for deciding whether or not the derived stream class can do this: CanRead, CanWrite and CanSeek. You can always consult these properties on the stream you're working with, to make sure that your desired operation (e.g writing) is available.

A Stream should always be disposed of whenever you're done working with it. Otherwise, it might hold a lock on a resource that should not be locked anymore, e.g. a file when using a FileStream. The Stream base class implements the IDisposable interface, so releasing it is as simple as calling the Dispose() method, or perhaps even better, encapsulating the use of the stream with a using() block (that's the approach we'll use in this tutorial).

Stream Readers & Writers

A common usage of streams is as the backing source for one of the Reader or Writer classes, e.g. FileReader or BinaryWriter. You can pass your Streams to a new instances of these classes to e.g. read an entire file, manipulate it in memory and then write it back - there's a lot of possibilities. We'll see this demonstrated in the next articles as well.

Summary

A stream is basically a mechanism for moving bytes from one place to another, e.g. into a file or from a network resource. The .NET framework uses the abstract Stream class as the base for all this, offering several derived implementations of it, e.g. FileStream and MemoryStream, which we'll discuss in the next articles.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!