C# StreamReader 与 BinaryReader?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10353913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:31:11  来源:igfitidea点击:

StreamReader vs BinaryReader?

c#.netfilestreamreaderbinaryreader

提问by Royi Namir

Both StreamReaderand BinaryReadercan be used to get data from binary file ( for example )

双方StreamReaderBinaryReader可以用来从二进制文件获取数据(例如)

BinaryReader :

二进制阅读器:

   using (FileStream fs = File.Open(@"c:.bin",FileMode.Open))
            {
                    byte[] data = new BinaryReader(fs).ReadBytes((int)fs.Length);
                    Encoding.getstring....
            }

StreamReader :

流阅读器:

  using (FileStream fs = File.Open(@"c:.bin",FileMode.Open))
            {
                using (StreamReader sr = new StreamReader(fs,Encoding.UTF8))
                {
                       var myString=sr.ReadToEnd();
                }
            }

What is the difference and when should I use which ?

有什么区别,我什么时候应该使用 which ?

采纳答案by Jon Skeet

Both StreamReader and BinaryReader can be used to get data from binary file

StreamReader 和 BinaryReader 均可用于从二进制文件中获取数据

Well, StreamReadercan be used to get text data from a binary representation of text.

好吧,StreamReader可用于从文本的二进制表示中获取文本数据。

BinaryReadercan be used to get arbitrary binary data. If some of that binary data happens to be a representation of text, that's fine - but it doesn't have to be.

BinaryReader可用于获取任意二进制数据。如果其中一些二进制数据恰好是文本的表示,那很好 - 但并非必须如此。

Bottom line:

底线:

  • If the entirety of your data is a straightforward binary encoding of text data, use StreamReader.
  • If you've fundamentally got binarydata which may happen to have someportions in text, use BinaryReader
  • 如果您的整个数据是文本数据的直接二进制编码,请使用StreamReader.
  • 如果您从根本上获得了可能碰巧在文本中包含某些部分的二进制数据,请使用BinaryReader

So for example, you wouldn'ttry to read a JPEG file with StreamReader.

因此,例如,您不会尝试读取带有StreamReader.