Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

c# - IO 101: Which are the main differences between TextWriter, FileStream and StreamWriter?

Let me first apologize if this question could sound perhaps sort of amateurish for the seasoned programmers among you, the thing is I've been having many arguments about this at work so I really want to get this straight and that's basically why I'm relying on the stackoverflow community to get this settled once and for all :)

So, on the one hand according to MSDN, we have:

TextWriter Class

Represents a writer that can write a sequential series of characters. This class is abstract.

FileStream Class

Exposes a Stream around a file, supporting both synchronous and asynchronous read and write operations.

StreamWriter Class

Implements a TextWriter for writing characters to a stream in a particular encoding.

On the other hand it's evident they all belong to System.IO but given that MSDN examples kind of mix some of them, I'm still not reaching the much desired a-ha moment.

Any comment would be more than appreciated, thanks much in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Streams handle bytes, Writers handle characters.

Bytes != characters. A character may take more than one byte to represent. The mapping from characters to bytes is called an encoding.

A FileStream refers to the bytes being written to a file, similar to how a MemoryStream refers to the bytes written to an in-memory buffer. In order to write characters to a stream, you'd need to convert them to a string of bytes. That's where a StreamWriter comes in to play. It takes a sequence of characters and an encoding, and turns it into a sequence of bytes.

A TextWriter is an interface (well, abstract base class) that all of the Writers must adhere to. It has all operations based on characters. The equivalent for bytes is the Stream abstract base class.

Things also go in the opposite direction. There is a TextReader abstract base class, describing how to read characters from somewhere, and a StreamReader, which allows you to read characters from a byte-oriented stream supplying an encoding - but this time used in reverse, to aggregate any multi-byte sequences into single characters where appropriate.

A Stream can be used for both reading and writing, since bytes are the lowest-level items used in I/O operations.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...