Saturday 13 May 2017

Streams 01 MemoryStream

Streams are abstractions of byte arrays. they are used to to read, write, and look through a sequence of bytes. The base class is Stream, however it is abstract, meaning that it cant actually be instantiated, it has to be inherited. Decedents of Stream are:

  • FileStream - reads & writes files
  • IsolatedStorageFileStream - Reads & wrties files in Isolated Storage
  • MemoryStream - Reads & writes data to memory
  • BufferedStream - Used to store bytes in memory to cache data
  • NetworkStream - reads & writes Data over a network socket
  • PipeStream - reads & writes data over an anonymous or named pipes
  • CryptoStream - Used to link data streams to cryptographic transformations 

Streams are used for reading or writing to byte arrays. For example

using System;
using System.IO;
using System.Text;

namespace pc.SimpleStreams
    class Program
        static void Main(string[] args)
            //Create byte array holding bytes for string
            byte[] helloWorld = Encoding.ASCII.GetBytes("hello world");

            //Create byte array of eqaul size
            byte[] HELLOWORLD = new byte[helloWorld.Length];

            //user two memory streams one to itterate over bytes
            //the second to write those bytes transformed into
            using (var ms = new MemoryStream(helloWorld))
            using (var MS = new MemoryStream(HELLOWORLD))
                int value = ms.ReadByte();
                while (value != -1)
                    MS.WriteByte((byte)(value - 32));
                    value = ms.ReadByte();
            //output contenets of byte array as string

What we do here is create a byte array that holds the values for our string, we then created a second array of equal size. we instantiate two memory streams one for each array and we use the one with values as the source; as we read values out of the first memory stream we decrease them by 32 which is the integer difference between lowercase and capital letters thus transforming our data to uppercase.