Custom .NET Stream Classes

Writing and testing custom .NET Stream classes are tasks which are not well understood by developers and testers. One of the first things .NET developers learn is how to read and write text files. For example this code uses a built-in FileStream class to read a text file and display its contents in hexadecimal:
Console.WriteLine("Reading TextFile1.txt with StreamReader.");
FileStream fs = new FileStream("..\\..\\TextFile1.txt",
StreamReader sr = new StreamReader(fs);
string s = sr.ReadToEnd();
Console.WriteLine("TextFile1.txt contains: " + s);
byte[] bytes = Encoding.ASCII.GetBytes(s);
Console.WriteLine("File in hexadecimal   : " +
A FileStream object is a programming abstraction that allows you to easily Read from, and Write to, a file without having to deal with the many low-level details that actually occur behind the scenes. Now suppose you write a custom .NET Stream class named RotateStream with a Write method that does some sort of bit-rotation to the right, and a Read method which does an opposite bit-rotation to the left. You can think of the Write method as an encoder and the Read method as a decoder. Now consider this code:
FileStream fs = new FileStream("..\\..\\TextFile1.txt",
Console.WriteLine("Filtering TextFile1.txt through custom RotateStream");
RotateStream rs = new RotateStream(fs);
int b = rs.ReadByte();
Console.WriteLine("First byte through the transform is " +
  b.ToString("X") + "h");
This code shows you how to use the RotateStream class. One of the reasons why many application developers and testers are not familiar with custom stream classes is that custom stream classes are not absolutely essential. By this statement I mean you can achieve the result of a custom stream implementation without actually creating a custom stream class — you can achieve the same effect produced by a custom stream class by using built-in .NET stream classes combined with byte-level programming techniques. So, why write a custom stream class? There are two main reasons. First, because a custom .NET stream is an abstraction of a sequence of bytes creating a custom stream class provides you with a generic view of all types of input and output, isolating you from the specific details of the underlying devices. Second, by wrapping byte-level input, output, and transformation routines into a class, you modularize your code making it easier to test and maintain.
This entry was posted in Software Test Automation. Bookmark the permalink.