What is the difference between calling Stream.Write and using a StreamWriter?

Posted by John Nelson on Stack Overflow See other posts from Stack Overflow or by John Nelson
Published on 2010-05-21T12:52:11Z Indexed on 2010/05/21 13:00 UTC
Read the original article Hit count: 238

Filed under:
|
|

What is the difference between instantiating a Stream object, such as MemoryStream and calling the memoryStream.Write() method to write to the stream, and instantiating a StreamWriter object with the stream and calling streamWriter.Write()?

Consider the following scenario:

You have a method that takes a Stream, writes a value, and returns it. The stream is read from later on, so the position must be reset. There are two possible ways of doing it (both seem to work).

// Instantiate a MemoryStream somewhere
//     - Passed to the following two methods
MemoryStream memoryStream = new MemoryStream();

// Not using a StreamWriter
private static Stream WriteToStream(Stream stream, string value)
{
    stream.Write(Encoding.Default.GetBytes(value), 0, value.Length);
    stream.Flush();
    stream.Position = 0;
    return stream;
}

// Using a StreamWriter
private static Stream WriteToStreamWithWriter(Stream stream, string value)
{
    StreamWriter sw = new StreamWriter(stream);
    sw.Write(value, 0, value.Length);
    sw.Flush();
    stream.Position = 0;
    return stream;
}

This is partially a scope problem, as I don't want to close the stream after writing to it since it will be read from later. I also certainly don't want to dispose it either, because that will close my stream. The difference seems to be that not using a StreamWriter introduces a direct dependency on Encoding.Default, but I'm not sure that's a very big deal. What's the difference, if any?

© Stack Overflow or respective owner

Related posts about c#

Related posts about memorystream