Writing to Memory Streams in C#

Picking up from where we left off from stream reading, this time we’ll be discussing writing.

Here is the code below we will be discussing.

private MemoryStream stream;

1 public void Write(string message) {
2        using (StreamWriter streamWriter = new StreamWriter (stream)) {

3        streamWriter.Write (message);
4        streamWriter.Flush ();
}
}

Line 1 is our method declaration and we will be passing in a string argument.
Line 2 has the keyword “using”, which makes certain that we expose of the streamWriter object once it’s been used.
Streamwriter is a class that implements, TextWriter it is used for writing characters to a stream using encoding(default encoding is used if not specified)

In this line it’s taking a MemoryStream object.

Line 3 uses the write method which can take a plethora of object types, such as ‘Char’, ‘String’, ‘Double’, look in the MSDN documentation for more details.

The methods writes a text representation to the stream, which is nice and handy.

Line 4 Will flush the stream writer meaning it will clear out the buffer but the stream will remain open. To close the stream we can call StreamWriter’s close method.
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