Home > Articles > Operating Systems, Server > Microsoft Windows Desktop

  • Print
  • + Share This
This chapter is from the book

Streams, Buffers, and Byte Arrays

The traditional method for reading data from a file, website, or other source in .NET is to use a stream. A stream enables you to transfer data into a data structure that you can read and manipulate. Streams may also provide the ability to transfer the contents of a data structure back to the stream to write it. Some streams support seeking, finding a position within a stream the same way you might skip ahead to a different scene on a DVD movie.

Streams are commonly written to byte arrays. The byte array is the preferred way to reference binary data in .NET. It can be used to manipulate data like the contents of a file or the pixels that make up the bitmap for an image. Many of the stream classes in .NET support converting a byte array to a stream or reading streams into a byte array. You can also convert other types into a byte array using the BitConverter class. The following example converts a 64-bit integer to an array of 8 bytes (8 bytes x 8 bits = 64 bits) and then back again:

var bigNumber = 4523452345234523455L;
var bytes = BitConverter.GetBytes(bigNumber);
var copyOfBigNumber = BitConverter.ToInt64(bytes, 0);
Debug.Assert(bigNumber == copyOfBigNumber);

The Windows Runtime introduces the concept of an IBuffer that behaves like a cross between a byte array and a stream. The interface itself only provides two members: a Capacity property (the maximum number of bytes that the buffer can hold) and a Length property (the number of bytes currently being used by the buffer). Many operations in the Windows Runtime either consume or produce an instance of IBuffer.

It is easy to convert between streams, byte arrays, and buffers. The methods to copy a stream into a byte array or send a byte array into a stream already exist as part of the .NET Framework. The WindowsRuntimeBufferExtensions class provides additional facilities for converting between buffers and byte arrays. It exists in the System.Runtime.InteropServices.WindowsRuntime namespace. It provides another set of extension methods including AsBuffer (cast a Byte[] instance to an IBuffer), AsStream (cast an IBuffer instance to a Stream), and ToArray (cast an IBuffer instance to a Byte[] instance).

  • + Share This
  • 🔖 Save To Your Account