Sounds easy doesnt it!? Well it is, eventually …

Well this simple task sure proved I had no clue on using any of the stream classes (apart from cut + paste specific examples from the web).

Like some (most?) developers (hackers?) I sat down with intellisense and started nessing around with

Stream st = new …

nope stream is an abstract class.

StringReader sr = …

It’s got string in the name right? This should take 10 seconds.

Yes you can easily create one of these, but cast to (Stream) sr doesn’t work!, why? time to look at the stream inheritance hierarchy.

This diagram from http://blogs.msdn.com/bindeshv/archive/2008/07/24/file-io-system-in-net.aspx sort of shows it.

As does this –

Hierarchy

 Excuse the awful scan, but you can just make it out.

Basically StringReader/Writer inherits from TextReader/Writer which inherits from System.IO (off top left).

This does not touch stream, so it looks like we need to use a MemoryStream. Like so –

MemoryStream memStream = new MemoryStream();

byte[] data = Encoding.UTF8.GetBytes(“XML long string”);

memStream.Write(data, 0, data.Length);

memStream.Position = 0; // we can also ensure reset stream for consumption

http://weblogs.asp.net/whaggard/archive/2004/09/23/233535.aspx says it far more succintly (choose your encoding as you require)

Stream s = new MemoryStream(ASCIIEncoding.Default.GetBytes(“Test String”));

Cheers.

Advertisements