What is the purpose of StreamReader when Stream.Read() exists?

做~自己de王妃 提交于 2019-11-30 07:27:21

问题


This has been bugging me. I know Stream is an abstract class and therefore can't be instantiated but it has classes that are derived from it. Why is there a StreamReader class and a Stream.Read() method (and vice verse for StreamWriter and Stream.Write())? You can write to a text file using 3 million different methods and it's rather frustrating trying to get my head around all of these different types and methods in the System.IO namespace. I found questions and answers regarding the differences between the writer and reader objects or the derived stream objects themselves but nothing regarding this particular case.


回答1:


TextReader (which StreamReader is derived from) works with strings. Stream works with bytes. The conversion between text and bytes is performed by an Encoding.

Choose the right class based on whether the contents of your file text or binary.

It is important to understand the difference between text and bytes.




回答2:


A StreamReader is a TextReader which means it is a Stream wrapper. A TextReader will convert (or encode) Text data (string or char) to byte[] and write them down to the underlying Stream.

Looking at the difference between the two implementations, you can see that StreamReader derives from TextReader, which, as declared, deals with text instead of bytes. It seems to me as an abstraction for users who want to work with textual representation. Of course, the underlying implementation will need a Stream to consume such data, but will provide a level of abstraction for end users.




回答3:


These two cases are used in different scenario

When you are using the stream class you can access the file for read and write. But when you use streamreader class you can use it to read only. This prevent the usage of file to be written. Sometimes This class is used for security purpose. e.g. for system files which are readonly.



来源:https://stackoverflow.com/questions/27648464/what-is-the-purpose-of-streamreader-when-stream-read-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!