So here’s the deal: I’m trying to open a file (from bytes), convert it to a string so I can mess with some metadata in the header, convert it back to bytes, and save it. The problem I’m running into right now is with this code. When I compare the string that’s been converted back and forth (but not otherwise modified) to the original byte array, it’s unequal. How can I make this work?
public static byte[] StringToByteArray(string str)
{
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(str);
}
public string ByteArrayToString(byte[] input)
{
UTF8Encoding enc = new UTF8Encoding();
string str = enc.GetString(input);
return str;
}
Here’s how I’m comparing them.
byte[] fileData = GetBinaryData(filesindir[0], Convert.ToInt32(fi.Length));
string fileDataString = ByteArrayToString(fileData);
byte[] recapturedBytes = StringToByteArray(fileDataString);
Response.Write((fileData == recapturedBytes));
I’m sure it’s UTF-8, using:
StreamReader sr = new StreamReader(filesindir[0]);
Response.Write(sr.CurrentEncoding);
which returns “System.Text.UTF8Encoding”.
Try the static functions on the
Encodingclass that provides you with instances of the various encodings. You shouldn’t need to instantiate theEncodingjust to convert to/from a byte array. How are you comparing the strings in code?Edit
You’re comparing arrays, not strings. They’re unequal because they refer to two different arrays; using the
==operator will only compare their references, not their values. You’ll need to inspect each element of the array in order to determine if they are equivalent.