本文介绍了为什么StreamReader返回字符串而不是字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两个相关问题:


  1. 为什么选择从中返回 string StreamReader.ReadToEnd()而不是 byte []

  2. 我知道我可以使用 System.Text.Encoding 进行转换,但是究竟应该使用哪种编码? UTF8,UTF7,ASCII还是Unicode?我正在处理二进制文件。

  1. Why did they choose to return string from StreamReader.ReadToEnd() instead of byte[]?
  2. I know I can convert it using System.Text.Encoding, but exactly which encoding should I use? UTF8, UTF7, ASCII or Unicode? I'm dealing with binary files.

注意:有人要求我澄清一下。只是单词 stream 给人以字节级别的印象……嗯... stream 数据(想想网络流,文件流,缓冲区,它们应该是char型概念)。正如乔尔(Joel)在回答中正确指出的那样,这更是一个命名问题。

Note: I was asked for clarification. It is just that the word stream gives an impression of byte-level...well...stream of data (think network stream, file stream, buffer, none of them is supposed to be a char-type concept). As correctly indicated by Joel in his answer, this is more of a naming issue than anything else.

推荐答案

为什么的问题是很少有什么是Stack Overflow的好饲料,因为真正能够回答它们的只有产品设计委员会的人员。

"Why" questions are rarely good fodder for Stack Overflow, since the only ones who can really answer them are those on the design committee for the product.

但是,在这种情况下,我们至少可以通过将您指向,您会在这里找到:

However, in this case we can at least give you a good indication by pointing you to the StreamReader documentation, where you'll find this:

因此,我们看到,使用文本而不是字节是StreamReader的全部目的。也许你会问为什么它被命名为 StreamReader而不是 TextStreamReader,但是随后我不得不把你引回到我的第一句话。

So we see, then, that working with text rather than bytes is what StreamReader is all about. Maybe you would ask why it's named "StreamReader" rather than "TextStreamReader", but then I'd have to refer you back to my first sentence.

字节数组...取决于您要执行的操作。 .Net使用 Unicode 作为字符串,但是底层流可能有所不同,而您打算使用此数据进行的任何操作都可能要求完全不同的编码。

As for getting a byte array... it depends on what you want to do. .Net uses Unicode for it's strings, but the underlying stream might be something different, and whatever you plan to do with this data might demand a different encoding entirely.

在这种情况下,您有二进制文件,并且需要 Byte [] 。而不是完全弄乱流,只需查看。如果必须处理流,则可能还需要。

In this case, though, you have binary files, and you want a Byte[]. Rather than messing with streams at all, just look at File.ReadAllBytes(). If you have to deal with streams you might also want a BinaryReader.

这篇关于为什么StreamReader返回字符串而不是字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 20:45