I have a stream that gets converted into a byte array.
I then take that bye array and turn it into a string.
When I try to turn that string back into a byte array it is not correct…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);
}
}
}
Without having more information, I’m quite certain that this is a text encoding issue. Most likely, the text encoding in the stream is different than the encoding specified as your parameter. This will result in different values at the byte level.
Here’s a few good articles that explains why you’re seeing what you’re seeing.