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.
- 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();
You May Also Like
ArrayList Class
Resizeable, unordered, index-based collection. Suffers from boxing/unboxing when working with value types. Implements IEnumerator, allowing foreach…
BinaryReader Class and BinaryWriter Class
Used to read and write binary data from streams. Call the correct Read methods when using a BinaryReader.
BitArray Class
Contains an array of true/false values. Resizable through the Length property. Supports bitwise operations.



