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

StreamWriter is a superclass of Stream that implements a TextWriter for easier handling of text. But since is a super class it has all the same methods in addition to the text handling ones. This why you need the Encoding.Default.GetBytes(value) in the first example and in the second you do not.


In terms of byte[] arrays, nothing, StreamWriter does introduce other more useful methods though for working with other types.


With the StreamWriter you have higher level overloads that can write various types to the stream without you worrying about the details. For example your code

sw.Write(value, 0, value.Length);

Could actually just be

sw.Write(value);

Using the StreamWriter.Write(string) overload.


One difference is that new StreamWriter(stream) by default uses UTF-8 encoding, so it will support Unicode data. Encoding.Default (at least on my machine) is a fixed-size code page (such as Windows-1250) and only supports ASCII and a limited set of national characters (256 different characters in total).

You really shouldn't do the following:

stream.Write(encoding.GetBytes(value), 0, value.Length);

It's just a coincidence that the encoding you use has a fixed size of 1 byte. (It wouldn't work with UTF-16, or with UTF-8 and non-ASCII data.) Instead, if you need to directly write to a stream, do:

byte[] byteData=encoding.GetBytes(value);
stream.Write(byteData, 0, byteData.Length);