TheDeveloperBlog.com


C# BaseStream Property

BaseStream is a property on a Stream. It returns information about the underlying buffer. BaseStream is available on all derived Stream instances. This property is useful in many programs.

Stream

Example. First, this program uses two System.IO objects. The MemoryStream stores the bytes in the specific file. And the BinaryReader type exposes the BaseStream property. The two using-statements enclose the BinaryReader object.

Using

Tip: You can see that the BaseStream returns a reference to the MemoryStream instance that was passed to the BinaryReader.

C# program that uses BaseStream property

using System;
using System.IO;

class Program
{
    static void Main()
    {
	using (MemoryStream memory = new MemoryStream(File.ReadAllBytes("C:\\P.bin")))
	using (BinaryReader reader = new BinaryReader(memory))
	{
	    // Get the BaseStream Stream.
	    Stream baseStream = reader.BaseStream;

	    // The BaseStream is the MemoryStream instance.
	    Console.WriteLine(baseStream.Length == memory.Length);
	    Console.WriteLine(baseStream is MemoryStream);
	}
    }
}

Output

True
True

Type of BaseStream. You can also see in the output of the program that the Stream returned by BaseStream is precisely equivalent to the MemoryStream. It is, however, referenced through its base class Stream.

MemoryStream

Discussion. The BaseStream property is defined on several types, including BinaryWriter, BinaryReader, StreamWriter and StreamReader. The best reason to use BaseStream is if your program's design doesn't allow you to directly access the base stream.

BinaryWriterBinaryReaderStreamWriterStreamReader

If you design a method that receives a BinaryReader parameter directly, you can call BaseStream to get the underlying Stream reference. In the example shown above, we could easily access the MemoryStream. This is not always possible.


Summary. BaseStream is useful when using classes that act upon underlying Streams. Often we need a reference to the original Stream to get its total Length or type. This helps when developing methods that receive types with underlying Streams.