MemoryStream Class

Overview

  • Provides an in-memory implementation of a Stream.
  • Is meant for temporary streams.
    • Possibly to minimize the time you need to hold another stream open, e.g.: locking a file with FileStream.

Good practice

  • Remember to call Close on a stream.
    • Make sure to call them in the right order, and not too early. See the example below, where closing 'b' to early would close 'a' as well.

Examples

Write to File

// MemoryStreams are usually temporary streams
// intended to be written to another stream later
MemoryStream a = new MemoryStream();
StreamWriter b = new StreamWriter(a);
 
b.WriteLine("Hello World");
b.WriteLine("Bye Bye!");
b.Flush();
 
FileStream c = File.Create(@"C:\Public\TestMem.txt");
a.WriteTo(c);
 
c.Close();
b.Close();
a.Close();