TOC

This article is currently in the process of being translated into Portuguese (~13% done).

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

Uma stream é basicamente um mecanismo para mover bytes de um lugar para outro, e.g. dentro de um arquivo ou de um recurso de rede. O .NET framework usa a classe abstrata Stream como base para tudo isso, oferecendo várias implementações derivadas disso, e.g. FileStream and MemoryStream, as quais iremos discutir no próximo artigo.


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!