Memory Streams

To emphasize I/O is much more than just files, let’s start by using streams to look at in-memory data. The following code uses a byte array as an in-memory storage for data that gets surfaced through two memory streams. Each stream has an offset in the array and can be marked as read-only. In some sense, a stream acts as a “view” of the underlying raw data.

var bs = new byte[20];var ms1 = new MemoryStream(bs, index:  5, count: 10, writable: true);var ms2 = new MemoryStream(bs, index: 10, count: 10, writable: false);ms1.Seek(5, SeekOrigin.Begin);     //      @ relative =  5, absolute = 15ms1.Write(new byte[] { 9, 8, 7 }, 0, 3);Console.WriteLine(bs[10]);         // 0x09 @                absolute = 10 ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.