c# - Is data “lost” when using binary data in a string?

后端 未结 9 1755
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-16 13:58

I\'ve tried reading a JPG file using the StreamReader class\' ReadToEnd() method which returns a string.

For some reason though, when I wri

相关标签:
9条回答
  • 2021-01-16 14:43

    Strings are for text data. They're not for binary data - if you use them this way you will lose data (there are encodings you can use which won't lose data if you're lucky, but there are subtle issues which still make it a really bad idea.)

    If you're actually dealing with a file, the easiest way of reading the whole thing is to call File.ReadAllBytes. If you have to deal with an arbitrary stream, have a look at "Creating a byte array from a stream".

    0 讨论(0)
  • 2021-01-16 14:48

    Strings are used to represent text. They are good at representing text. Very good, in fact, as they support Unicode and protect you from all sorts of typical string processing bugs.

    They aren't good at representing binary data, because that isn't what they're designed for. As you mention, a byte array is much better for this.

    It's not a matter of one being better than the other, it's simply fitness for purpose and understanding when to choose one or the other. Text = string, binary = byte array or stream.

    0 讨论(0)
  • 2021-01-16 14:50

    Always remember, text data is binary data but binary data is not text data.

    0 讨论(0)
提交回复
热议问题