Thursday, April 25, 2013

Sasa.IO.Streams - Convenient Stream Extensions

This is the sixteenth post in my ongoing series covering the abstractions in Sasa. Previous posts:

Streams are a pervasive component of .NET I/O, but the standard stream interface is missing a few convenient extensions, if only needed for testing and debugging purposes. Sasa.IO.Streams provides a few simple extension methods to simplify working with streams.

Sasa.IO.Streams.CopyTo

Sasa.IO.Streams.CopyTo is a set of extension methods to copy data from one stream to another:

var source = new MemoryStream(Encoding.ASCII.GetBytes("Hello world!"));
var target = new MemoryStream();
source.CopyTo(target);
Console.WriteLine(Encoding.ASCII.GetString(target.ToArray()));
// output:
// Hello world!

There is also an overload explicitly specifying the number of bytes to copy.

Sasa.IO.Streams.ToArray

Sasa.IO.Streams.ToArray dumps the contents of any stream into a byte[]:

// write contents to file
using (var fs = File.OpenWrite("foo.txt"))
{
    fs.Write(Encoding.ASCII.GetBytes("Hello world!"));
}
// read contents from file in one go
byte[] data;
using (var fs = File.OpenRead("foo.txt"))
{
    data = fs.ToArray();
}
Console.WriteLine(Encoding.ASCII.GetString(data));
// output:
// Hello world!

No comments: