Question:
What is different 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?
The StreamWriter class in C# is used for writing characters to a stream. It uses the TextWriter class as a base class and provides the overload methods for writing data into a file. The StreamWriter is mainly used for writing multiple characters of data into a file.
A StreamReader is used whenever data is required to be read from a file. A Streamwriter is used whenever data needs to be written to a file.
As the name suggests, a FileStream reads and writes to a file whereas a MemoryStream reads and writes to the memory. So it relates to where the stream is stored.
The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These classes inherit from the abstract base class Stream, which supports reading and writing bytes into a file stream.
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 type like string, int and char to byte[]
and then writes hat 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With