title: C# - Comparing strings of different encodings
body: <p>Using C#, I fetch a <code>TextBox.Text</code> value from an .ascx page. When I compare the equality of the value to a regular string object inside a LINQ-query, it always returns false.</p>
  
  <p>I have come to the conclusion that they are differently encoded, but have so far had no luck in converting or comparing them. </p>
  
  <pre><code>docname = "Testdoc 1.docx"; //regular string created in C#
  fetchedVal = ((TextBox)e.Item.FindControl("txtSelectedDocs")).Text; //UTF-8
  </code></pre>
  
  <p>The above two strings are identical when represented as literals, but comparing the <code>byte[]</code> they are obviously different due to the encoding.</p>
  
  <p>I've tried alot of different things, such as:</p>
  
  <pre><code>System.Text.Encoding.Default.GetString(utf8.GetBytes(fetchedVal));
  </code></pre>
  
  <p>but that will return the value <code>"TestdocÂ 1.docx"</code>.</p>
  
  <p>If I instead try </p>
  
  <pre><code>System.Text.Encoding.Default.GetString(System.Text.Encoding.Default.GetBytes(fetchedVal));
  </code></pre>
  
  <p>it returns <code>"Testdoc 1.docx"</code> but an <code>Equals()</code>-check still returns <code>false</code>.</p>
  
  <p>I have also tried the following, which seem to be the recommended approach, but with no luck:</p>
  
  <pre><code>byte[] utf8Bytes = Encoding.UTF8.GetBytes(fetchedVal);
  byte[] unicodeBytes = Encoding.Convert(Encoding.UTF8, Encoding.Unicode, utf8Bytes);
  string fetchedValConverted = Encoding.Unicode.GetString(unicodeBytes);
  </code></pre>
  
  <p>The culprit appears to be the whitespace, because when examining the byte sequence it's always the seventh byte that differs.</p>
  
  <p>How do you properly convert from UTF-8 to default string encoding in C#?</p>