Reading Memory Streams in C#

I have been working with streams the last couple of days and they were confusing at first, especially the way C# does it differently to Java.

With the help of MSDN and nearby kind craftspeople, it’s beginning to become clearer.

We will use a simple example to explain how they work.

Let say we want to create a console that reads and writes to a stream. Luckily for us in C# we have a handy class called ‘MemoryStream’ which shockingly creates a stream.

We can pass this MemoryStream into our constructor like so

public AwesomeConsole (MemoryStream stream) {
this.stream = stream;
}

We are assigning it to a private field here so we can use it later in our read and write methods.

Lets move on to the Read method.

public string Read () {
var streamReader = new StreamReader (stream);
return streamReader.ReadToEnd ();
}

Here we are using the ‘var’ keyword which does away for the need for explicitly type declarations which is quite nice (not at the time though)

We instantiate a new StreamReader object, passing a ‘Stream’ to it’s constructor.

The StreamReader class reads characters from a byte stream, depending on the characters that you’re willing to accept, you may have to include a require Encoding such as UTF8Encoding. For the sake of simplicity we won’t doing that.

Streams are like old fashion cassette tapes( go further back, Betamax tapes), in that we can rewind them, fast forward to a moment in the stream. In this case we want to read to the end of the stream using the appropriately name method ‘ReadToEnd’ which returns us our string object.

Tomorrow will be part 2… writing to streams.

Ced

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s