String back to byte array - not working

I have a stream that converts to an array of bytes.

Then I take this bye array and turn it into a string.

When I try to turn this string back into an array of bytes, this is wrong ... see the code below.

private void Parse(Stream stream, Encoding encoding) { // Read the stream into a byte array byte[] allData = ToByteArray(stream); // Copy to a string for header parsing string allContent = encoding.GetString(allData); //This does not convert back right - just for demo purposes, not how the code is used allData = encoding.GetBytes(allContent); } private byte[] ToByteArray(Stream stream) { byte[] buffer = new byte[32768]; using (MemoryStream ms = new MemoryStream()) { while (true) { int read = stream.Read(buffer, 0, buffer.Length); if (read <= 0) return ms.ToArray(); ms.Write(buffer, 0, read); } } } 
+4
source share
2 answers

Without additional information, I am quite sure that this is a problem with text encoding. Most likely, the text encoding in the stream is different from the encoding specified as your parameter. This will result in different values ​​at the byte level.

Here are some good articles explaining why you see what you see.

+2
source

I think that changing the ToByteArray method to use StreamReader , which corresponds to the encoding, should work in this case, although without seeing more code, I can not be sure.

 private byte[] ToByteArray(Stream stream, System.Text.Encoding encoding) { using(var sr = new StreamReader(stream, encoding)) { return encoding.GetBytes(sr.ReadToEnd()); } } 

EDIT
Since you are working with image data, you should use Convert.ToBase64String to convert byte[] to string . Then you can use Convert.FromBase64String decoding to convert back to byte[] . The reason encoding.GetBytes does not work, because there may be some data in byte[] that cannot be represented as a string for this encoding.

 private void Parse(Stream stream, Encoding encoding) { byte[] allData = ToByteArray(stream); string allContent = Convert.ToBase64String(allData); allData = Convert.FromBase64String(allContent); } 
+2
source

All Articles