Reputation: 35380
Two related questions:
string
from StreamReader.ReadToEnd()
instead of byte[]
? System.Text.Encoding
, but exactly which encoding should I use? UTF8, UTF7, ASCII or Unicode? I'm dealing with binary files.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.
Upvotes: 1
Views: 3683
Reputation: 415600
"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:
Implements a TextReader that reads characters from a byte stream in a particular encoding.
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.
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.
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
.
Upvotes: 5
Reputation: 3837
You have a number of alternatives to StreamReader, which is used mostly for reading in character data. If you are reading in binary file data, then a better option is to use FileStream.Read. It returns the data in a byte array.
According to my benchmarks, it is faster than BinaryReader and File.ReadAllBytes. But, File.ReadAllBytes is easier to use.
Upvotes: 1