Search code examples
c#iofilestreamstreamwriter

FileStream vs/differences StreamWriter?


What is difference between FileStream and StreamWriter in .NET?

What context are you supposed to use it? What is their advantage and disadvantage?

Is it possible to combine these two into one?


Solution

  • What is different between FileStream and StreamWriter in dotnet?

    A FileStream is a Stream. Like all Streams it only deals with byte[] data.

    A StreamWriter : TextWriter is a Stream-decorator. A TextWriter encodes the primitive types like string, int and char to byte[] and then writes that to the linked Stream.

    What context are you supposed to use it? What is their advantage and disadvantage?

    You use a bare FileStream when you have byte[] data. You add a StreamWriter when you want to write text. Use a Formatter or a Serializer to write more complex data.

    Is it possible to combine these two into one?

    Yes. You always need a Stream to create a StreamWriter. The helper method System.IO.File.CreateText("path") will create them in combination and then you only have to Dispose() the outer writer.