title: Converting byte array to string and back again in C#
body: <p>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?</p>
  
  <pre><code>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;
  }
  </code></pre>
  
  <p>Here's how I'm comparing them.</p>
  
  <pre><code>byte[] fileData = GetBinaryData(filesindir[0], Convert.ToInt32(fi.Length));
  string fileDataString = ByteArrayToString(fileData);
  byte[] recapturedBytes = StringToByteArray(fileDataString);
  Response.Write((fileData == recapturedBytes));
  </code></pre>
  
  <p>I'm sure it's UTF-8, using:</p>
  
  <pre><code>StreamReader sr = new StreamReader(filesindir[0]);
  Response.Write(sr.CurrentEncoding);
  </code></pre>
  
  <p>which returns "System.Text.UTF8Encoding".</p>