title: Detect encoding of byte array C#
body: <p>Is there any way to determine a byte array's encoding in C#?</p>
  
  <p>I have any string, like  <strong>"Lorem ipsum áéíóú ñÑç"</strong>, and I get bytes array using several encodings.</p>
  
  <p>I would like a only method for detect encoding in byte array and I get string value again.</p>
  
  <p>Other issue, maybe, I'll have a column in database which store BLOB (like byte array).
  A string previously converted to byte array in UTF-8. Maybe another application converts a string to byte array using Unicode encoding.</p>
  
  <p>In a database column there are byte arrays in several encodings. It would be very useful detect byte array's encoding. I need a way to find encoding of byte array.</p>
  
  <p>Tests:</p>
  
  <pre><code>string DataXmlForSupport = "&lt;support&gt;&lt;machinename&gt;&lt;/machinename&gt;&lt;comments&gt;Este es el log 1 áéíóú&lt;/comments&gt;&lt;/support&gt;";
          string DataXmlForSupport2 = "Lorem ipsum áéíóú ñÑç";
  
          [TestMethod]
          public void Encoding_byte_array_string()
          {
              var uencoding = new System.Text.UnicodeEncoding();
              byte[] data = uencoding.GetBytes(DataXmlForSupport);
  
              var dataXml = Encoding.Unicode.GetString(data);
              Assert.AreEqual(DataXmlForSupport, dataXml, "Se esperaba resultados Unicode");
  
              dataXml = Encoding.UTF8.GetString(data);
              Assert.AreNotEqual(DataXmlForSupport, dataXml, "NO Se esperaba resultados UTF8");
  
              var utf8 = new System.Text.UTF8Encoding();
              data = utf8.GetBytes(DataXmlForSupport2);
  
              dataXml = Encoding.UTF8.GetString(data);
              Assert.AreEqual(DataXmlForSupport2, dataXml, "Se esperaba resultados UTF8");
  
              dataXml = Encoding.Unicode.GetString(data);
              Assert.AreNotEqual(DataXmlForSupport2, dataXml, "NO Se esperaba resultados Unicode");
  
          }
  </code></pre>