Streams and Byte Streams in C#

This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.

Streams

Whether they contain water or data, streams evoke an image of efficient flow. Suppose you have to transfer water from one tank to another. You could repeatedly fill a bucket with water from one tank and empty it into the other tank. However, if you simply use a pipe to join the two tanks and let the water flow as a stream, your work becomes very fast and easy!

The same concept applies to the flow of data. Streams in C# allow you to carry data from one point to another quickly and efficiently. The data transfer can take place between files, sockets, objects, or even other streams.

Streams in CLR come in three forms: streams that read and write bytes, streams that read and write characters, and a stream to read and write primitive types. Table 6.4 lists the types of streams.

table-6.4.gif

Table 6.4: Streams in .NET

Byte Streams

Byte streams comprise classes that treat data in the stream as bytes. These streams are most useful when you work with data that is not in a format readable by humans.

Stream Class

In the CLR, the Stream class provides the base for other byte stream classes. If you want to implement your own byte-stream class, you have to override the Stream class, which is an abstract class. Table 6.5 highlights some of the properties of a stream.

table-6.5.gif

Table 6.5: Some Important Properties of a Stream

The Stream class provides support for both synchronous and asynchronous reading and writing of data through the methods outlined in Table 6.6.

table-6.6.gif

Table 6.6: Some Methods for Asynchronous Reads and Writes

Table 6.7 lists other methods you can use with the Stream class. Note that you should always call the Close method explicitly rather than depend upon the Garbage Collector (GC) to free any resources used by the stream.

table-6.7.gif

Table 6.7: Other Useful Methods

Conclusion


Hope this article would have helped you in understanding Streams and Byte Streams in C#. See other articles on the website on .NET and C#.

visual C-sharp.jpg The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.

Up Next
    Ebook Download
    View all
    Learn
    View all