Skip to content
David Cumps
Exam 70-536 study notes

MemoryStream Class

Part of my 2008 study notes for exam 70-536 (.NET Framework 2.0).

Overview

  • Provides an in-memory implementation of a Stream.
  • Meant for temporary streams.
    • For example, to minimize how long you hold another stream open, such as a FileStream that locks a file.

Good practice

  • Remember to call Close on a stream.
    • Make sure to call Close in the right order, and not too early. See the example below, where closing ‘b’ too 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();

You May Also Like