2009-06-22 22 views
109

¿Hay alguna forma de determinar la codificación de una cadena en C#?Determine la codificación de una cadena en C#

Digamos que tengo una cadena de nombre de archivo, pero no sé si está codificada en Unicode UTF-16 o la codificación predeterminada del sistema, ¿cómo puedo averiguarlo?

+0

no se puede "codificar" en Unicode. Y no hay forma de determinar automágicamente la codificación de cualquier cadena dada, sin ninguna otra información previa. – NicDumZ

+0

"No se puede 'codificar' en Unicode" - si interpretamos Unicode como UTF-16 (o cualquier otro UTF * específico), entonces esa es una forma perfectamente válida de escribir puntos de código como una secuencia de bytes (= codificación). –

+1

¿cómo puedes escribir tales aproximaciones? UTF-16 es una de las formas posibles de * codificar * datos Unicode. No puedes "codificar en Unicode"; Unicode no es UTF- *; y UTF- * no es Unicode. Lo sentimos, pero si seguimos escribiendo esas aproximaciones, ¿cómo cambiarán los comportamientos relacionados con Unicode? Los principiantes siempre se confundirán con el oscuro monstruo Unicode y las cosas nunca cambiarán. Seamos precisos – NicDumZ

Respuesta

28

Echa un vistazo a Utf8Checker es una clase simple que hace exactamente esto en código administrado puro. http://utf8checker.codeplex.com

Aviso: como ya se señaló "determinar la codificación" tiene sentido solo para las secuencias de bytes. Si tiene una cadena ya está codificada por alguien en el camino que ya sabía o adivinó la codificación para obtener la cadena en primer lugar.

+0

Si la cadena es una decodificación incorrecta hecha con un simple 8- Con la codificación de bit, y tiene la codificación utilizada para decodificarla, normalmente puede recuperar los bytes sin ningún tipo de corrupción. – Nyerguds

29

Depende de dónde provenga la cadena '. Una cadena .NET es Unicode (UTF-16). La única forma en que podría ser diferente si, por ejemplo, leer los datos de una base de datos en una matriz de bytes.

Este artículo CodeProject pueden ser de interés: Detect Encoding for in- and outgoing text

de Jon Skeet Strings in C# and .NET es una excelente explicación de las cadenas de .NET.

+0

Vino de una aplicación C++ que no es Unicode .. El artículo de CodeProject parece un poco demasiado complejo, sin embargo, parece hacer lo que quiero hacer ... Gracias. – krebstar

11

Otra opción, muy tarde en llegar, lo siento:

http://www.architectshack.com/TextFileEncodingDetector.ashx

Este C pequeña # clase -sólo utiliza listas de materiales, si está presente, trata de detectar automáticamente posibles codificaciones Unicode de otro modo, en verano y si ninguno de las codificaciones Unicode es posible o probable.

Suena como que UTF8Checker hace referencia arriba hace algo similar, pero creo que este es un alcance un poco más amplio: en lugar de solo UTF8, también busca otras posibles codificaciones Unicode (UTF-16 LE o BE) que podrían faltar BOM.

Espero que esto ayude a alguien!

+0

Código bastante agradable, resolvió mi problema de detección de codificación :) –

14

Sé que esto es un poco tarde - pero para ser claro:

Una cadena no tiene realmente la codificación ... en el .NET una cadena es una colección de objetos de carbonilla. Esencialmente, si se trata de una cadena, ya ha sido decodificada.

Sin embargo, si está leyendo el contenido de un archivo, que está hecho de bytes, y desea convertirlo en una cadena, entonces se debe usar la codificación del archivo.

.NET incluye clases de codificación y descodificación para: ASCII, UTF7, UTF8, UTF32 y más.

La mayoría de estas codificaciones contienen ciertas marcas de orden de bytes que se pueden usar para distinguir qué tipo de codificación se utilizó.

.NET class System.IO.StreamReader puede determinar la codificación utilizada en una secuencia, leyendo esas marcas de orden de bytes;

Aquí es un ejemplo:

/// <summary> 
    /// return the detected encoding and the contents of the file. 
    /// </summary> 
    /// <param name="fileName"></param> 
    /// <param name="contents"></param> 
    /// <returns></returns> 
    public static Encoding DetectEncoding(String fileName, out String contents) 
    { 
     // open the file with the stream-reader: 
     using (StreamReader reader = new StreamReader(fileName, true)) 
     { 
      // read the contents of the file into a string 
      contents = reader.ReadToEnd(); 

      // return the encoding. 
      return reader.CurrentEncoding; 
     } 
    } 
+2

Esto no funcionará para detectar UTF 16 sin la lista de materiales. Tampoco recurrirá a la página de códigos predeterminada local del usuario si no detecta ninguna codificación Unicode. Puede corregir esto último agregando 'Encoding.Default' como un parámetro StreamReader, pero luego el código no detectará UTF8 sin la BOM. –

+1

@DanW: ¿Sin embargo, UTF-16 sin BOM realmente está hecho? Nunca usaría eso; es inevitable que sea un desastre abrir prácticamente cualquier cosa. – Nyerguds

42

El código siguiente tiene las siguientes características:

  1. detección o intento de detección de UTF-7, UTF-8/16/32 (BOM, no bom, little & big endian)
  2. Retrocede a la página de códigos predeterminada local si no se encuentra codificación Unicode.
  3. Detecta (con alta probabilidad) archivos Unicode con la BOM/firma faltante
  4. Busca charset = xyz y encoding = xyz dentro del archivo para ayudar a determinar la codificación.
  5. Para guardar el procesamiento, puede "probar" el archivo (número de bytes definible).
  6. Se devuelve el archivo de texto codificado y decodificado.
  7. solución puramente basada en bytes para la eficiencia

Como otros han dicho, no hay solución puede ser perfecto (y sin duda uno no puede diferenciar fácilmente entre las distintas codificaciones extendido ASCII de 8 bits en el uso de todo el mundo), pero podemos conseguir 'lo suficientemente bueno', especialmente si el desarrollador también presenta al usuario una lista de codificaciones alternativas como se muestra aquí: What is the most common encoding of each language?

una lista completa de codificaciones se puede encontrar utilizando Encoding.GetEncodings();

// Function to detect the encoding for UTF-7, UTF-8/16/32 (bom, no bom, little 
// & big endian), and local default codepage, and potentially other codepages. 
// 'taster' = number of bytes to check of the file (to save processing). Higher 
// value is slower, but more reliable (especially UTF-8 with special characters 
// later on may appear to be ASCII initially). If taster = 0, then taster 
// becomes the length of the file (for maximum reliability). 'text' is simply 
// the string with the discovered encoding applied to the file. 
public Encoding detectTextEncoding(string filename, out String text, int taster = 1000) 
{ 
    byte[] b = File.ReadAllBytes(filename); 

    //////////////// First check the low hanging fruit by checking if a 
    //////////////// BOM/signature exists (sourced from http://www.unicode.org/faq/utf_bom.html#bom4) 
    if (b.Length >= 4 && b[0] == 0x00 && b[1] == 0x00 && b[2] == 0xFE && b[3] == 0xFF) { text = Encoding.GetEncoding("utf-32BE").GetString(b, 4, b.Length - 4); return Encoding.GetEncoding("utf-32BE"); } // UTF-32, big-endian 
    else if (b.Length >= 4 && b[0] == 0xFF && b[1] == 0xFE && b[2] == 0x00 && b[3] == 0x00) { text = Encoding.UTF32.GetString(b, 4, b.Length - 4); return Encoding.UTF32; } // UTF-32, little-endian 
    else if (b.Length >= 2 && b[0] == 0xFE && b[1] == 0xFF) { text = Encoding.BigEndianUnicode.GetString(b, 2, b.Length - 2); return Encoding.BigEndianUnicode; }  // UTF-16, big-endian 
    else if (b.Length >= 2 && b[0] == 0xFF && b[1] == 0xFE) { text = Encoding.Unicode.GetString(b, 2, b.Length - 2); return Encoding.Unicode; }    // UTF-16, little-endian 
    else if (b.Length >= 3 && b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF) { text = Encoding.UTF8.GetString(b, 3, b.Length - 3); return Encoding.UTF8; } // UTF-8 
    else if (b.Length >= 3 && b[0] == 0x2b && b[1] == 0x2f && b[2] == 0x76) { text = Encoding.UTF7.GetString(b,3,b.Length-3); return Encoding.UTF7; } // UTF-7 


    //////////// If the code reaches here, no BOM/signature was found, so now 
    //////////// we need to 'taste' the file to see if can manually discover 
    //////////// the encoding. A high taster value is desired for UTF-8 
    if (taster == 0 || taster > b.Length) taster = b.Length; // Taster size can't be bigger than the filesize obviously. 


    // Some text files are encoded in UTF8, but have no BOM/signature. Hence 
    // the below manually checks for a UTF8 pattern. This code is based off 
    // the top answer at: https://stackoverflow.com/questions/6555015/check-for-invalid-utf8 
    // For our purposes, an unnecessarily strict (and terser/slower) 
    // implementation is shown at: https://stackoverflow.com/questions/1031645/how-to-detect-utf-8-in-plain-c 
    // For the below, false positives should be exceedingly rare (and would 
    // be either slightly malformed UTF-8 (which would suit our purposes 
    // anyway) or 8-bit extended ASCII/UTF-16/32 at a vanishingly long shot). 
    int i = 0; 
    bool utf8 = false; 
    while (i < taster - 4) 
    { 
     if (b[i] <= 0x7F) { i += 1; continue; }  // If all characters are below 0x80, then it is valid UTF8, but UTF8 is not 'required' (and therefore the text is more desirable to be treated as the default codepage of the computer). Hence, there's no "utf8 = true;" code unlike the next three checks. 
     if (b[i] >= 0xC2 && b[i] <= 0xDF && b[i + 1] >= 0x80 && b[i + 1] < 0xC0) { i += 2; utf8 = true; continue; } 
     if (b[i] >= 0xE0 && b[i] <= 0xF0 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0 && b[i + 2] >= 0x80 && b[i + 2] < 0xC0) { i += 3; utf8 = true; continue; } 
     if (b[i] >= 0xF0 && b[i] <= 0xF4 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0 && b[i + 2] >= 0x80 && b[i + 2] < 0xC0 && b[i + 3] >= 0x80 && b[i + 3] < 0xC0) { i += 4; utf8 = true; continue; } 
     utf8 = false; break; 
    } 
    if (utf8 == true) { 
     text = Encoding.UTF8.GetString(b); 
     return Encoding.UTF8; 
    } 


    // The next check is a heuristic attempt to detect UTF-16 without a BOM. 
    // We simply look for zeroes in odd or even byte places, and if a certain 
    // threshold is reached, the code is 'probably' UF-16.   
    double threshold = 0.1; // proportion of chars step 2 which must be zeroed to be diagnosed as utf-16. 0.1 = 10% 
    int count = 0; 
    for (int n = 0; n < taster; n += 2) if (b[n] == 0) count++; 
    if (((double)count)/taster > threshold) { text = Encoding.BigEndianUnicode.GetString(b); return Encoding.BigEndianUnicode; } 
    count = 0; 
    for (int n = 1; n < taster; n += 2) if (b[n] == 0) count++; 
    if (((double)count)/taster > threshold) { text = Encoding.Unicode.GetString(b); return Encoding.Unicode; } // (little-endian) 


    // Finally, a long shot - let's see if we can find "charset=xyz" or 
    // "encoding=xyz" to identify the encoding: 
    for (int n = 0; n < taster-9; n++) 
    { 
     if (
      ((b[n + 0] == 'c' || b[n + 0] == 'C') && (b[n + 1] == 'h' || b[n + 1] == 'H') && (b[n + 2] == 'a' || b[n + 2] == 'A') && (b[n + 3] == 'r' || b[n + 3] == 'R') && (b[n + 4] == 's' || b[n + 4] == 'S') && (b[n + 5] == 'e' || b[n + 5] == 'E') && (b[n + 6] == 't' || b[n + 6] == 'T') && (b[n + 7] == '=')) || 
      ((b[n + 0] == 'e' || b[n + 0] == 'E') && (b[n + 1] == 'n' || b[n + 1] == 'N') && (b[n + 2] == 'c' || b[n + 2] == 'C') && (b[n + 3] == 'o' || b[n + 3] == 'O') && (b[n + 4] == 'd' || b[n + 4] == 'D') && (b[n + 5] == 'i' || b[n + 5] == 'I') && (b[n + 6] == 'n' || b[n + 6] == 'N') && (b[n + 7] == 'g' || b[n + 7] == 'G') && (b[n + 8] == '=')) 
      ) 
     { 
      if (b[n + 0] == 'c' || b[n + 0] == 'C') n += 8; else n += 9; 
      if (b[n] == '"' || b[n] == '\'') n++; 
      int oldn = n; 
      while (n < taster && (b[n] == '_' || b[n] == '-' || (b[n] >= '0' && b[n] <= '9') || (b[n] >= 'a' && b[n] <= 'z') || (b[n] >= 'A' && b[n] <= 'Z'))) 
      { n++; } 
      byte[] nb = new byte[n-oldn]; 
      Array.Copy(b, oldn, nb, 0, n-oldn); 
      try { 
       string internalEnc = Encoding.ASCII.GetString(nb); 
       text = Encoding.GetEncoding(internalEnc).GetString(b); 
       return Encoding.GetEncoding(internalEnc); 
      } 
      catch { break; } // If C# doesn't recognize the name of the encoding, break. 
     } 
    } 


    // If all else fails, the encoding is probably (though certainly not 
    // definitely) the user's local codepage! One might present to the user a 
    // list of alternative encodings as shown here: https://stackoverflow.com/questions/8509339/what-is-the-most-common-encoding-of-each-language 
    // A full list can be found using Encoding.GetEncodings(); 
    text = Encoding.Default.GetString(b); 
    return Encoding.Default; 
} 
+0

Esto funciona para cirílico (y probablemente todos los demás) archivos .eml (del encabezado del conjunto de caracteres del correo) –

+0

¡Muchas gracias! – supertopi

+0

UTF-7 no se puede decodificar ingenuamente, en realidad; su preámbulo completo es más largo e incluye dos bits del primer carácter. El sistema .Net parece no tener ningún soporte para el sistema de preámbulos de UTF7. – Nyerguds

5

Mi solución es usar productos incorporados con algunos inconvenientes.

Elegí la estrategia de una respuesta a otra pregunta similar en stackoverflow pero no puedo encontrarla ahora.

Primero comprueba la lista de materiales utilizando la lógica incorporada en StreamReader, si hay una lista de materiales, la codificación será distinta de Encoding.Default, y debemos confiar en ese resultado.

Si no, comprueba si la secuencia de bytes es una secuencia UTF-8 válida. si lo es, adivinará UTF-8 como la codificación, y si no, de nuevo, la codificación ASCII predeterminada será el resultado.

static Encoding getEncoding(string path) { 
    var stream = new FileStream(path, FileMode.Open); 
    var reader = new StreamReader(stream, Encoding.Default, true); 
    reader.Read(); 

    if (reader.CurrentEncoding != Encoding.Default) { 
     reader.Close(); 
     return reader.CurrentEncoding; 
    } 

    stream.Position = 0; 

    reader = new StreamReader(stream, new UTF8Encoding(false, true)); 
    try { 
     reader.ReadToEnd(); 
     reader.Close(); 
     return Encoding.UTF8; 
    } 
    catch (Exception) { 
     reader.Close(); 
     return Encoding.Default; 
    } 
} 
1

Nota: este fue un experimento para ver cómo codificación UTF-8 a una reflexión interna. The solution offered by vilicvane, para usar un objeto UTF8Encoding que se inicializa para lanzar una excepción en la falla de descodificación, es mucho más simple, y básicamente hace lo mismo.


de escribir este pedazo de código para diferenciar entre UTF-8 y Windows-1252. Sin embargo, no debería usarse para archivos de texto gigantescos, ya que carga todo en la memoria y lo escanea por completo. Lo usé para archivos de subtítulos .srt, solo para poder guardarlos en la codificación en la que se cargaron.

La codificación dada a la función como ref debe ser la codificación de respaldo de 8 bits para usar en caso de que el archivo se detecte como no válido UTF-8; generalmente, en sistemas Windows, este será Windows-1252.Sin embargo, esto no sirve para nada como comprobar rangos de ASCI válidos reales, y no detecta UTF-16 incluso en la marca de orden de bytes.

La teoría detrás de la detección a nivel de bits se puede encontrar aquí: https://ianthehenry.com/2015/1/17/decoding-utf-8/

Básicamente, el rango de bits del primer byte determina cuántos después de que forman parte de la entidad UTF-8. Estos bytes después están siempre en el mismo rango de bits.

/// <summary> 
///  Detects whether the encoding of the data is valid UTF-8 or ascii. If detection fails, the text is decoded using the given fallback encoding. 
///  Bit-wise mechanism for detecting valid UTF-8 based on https://ianthehenry.com/2015/1/17/decoding-utf-8/ 
///  Note that pure ascii detection should not be trusted: it might mean the file is meant to be UTF-8 or Windows-1252 but simply contains no special characters. 
/// </summary> 
/// <param name="docBytes">The bytes of the text document.</param> 
/// <param name="encoding">The default encoding to use as fallback if the text is detected not to be pure ascii or UTF-8 compliant. This ref parameter is changed to the detected encoding, or Windows-1252 if the given encoding parameter is null and the text is not valid UTF-8.</param> 
/// <returns>The contents of the read file</returns> 
public static String ReadFileAndGetEncoding(Byte[] docBytes, ref Encoding encoding) 
{ 
    if (encoding == null) 
     encoding = Encoding.GetEncoding(1252); 
    // BOM detection is not added in this example. Add it yourself if you feel like it. Should set the "encoding" param and return the decoded string. 
    //String file = DetectByBOM(docBytes, ref encoding); 
    //if (file != null) 
    // return file; 
    Boolean isPureAscii = true; 
    Boolean isUtf8Valid = true; 
    for (Int32 i = 0; i < docBytes.Length; i++) 
    { 
     Int32 skip = TestUtf8(docBytes, i); 
     if (skip != 0) 
     { 
      if (isPureAscii) 
       isPureAscii = false; 
      if (skip < 0) 
       isUtf8Valid = false; 
      else 
       i += skip; 
     } 
     // if already detected that it's not valid utf8, there's no sense in going on. 
     if (!isUtf8Valid) 
      break; 
    } 
    if (isPureAscii) 
     encoding = new ASCIIEncoding(); // pure 7-bit ascii. 
    else if (isUtf8Valid) 
     encoding = new UTF8Encoding(false); 
    // else, retain given fallback encoding. 
    return encoding.GetString(docBytes); 
} 

/// <summary> 
/// Tests if the bytes following the given offset are UTF-8 valid, and returns 
/// the extra amount of bytes to skip ahead to do the next read if it is 
/// (meaning, detecting a single-byte ascii character would return 0). 
/// If the text is not UTF-8 valid it returns -1. 
/// </summary> 
/// <param name="binFile">Byte array to test</param> 
/// <param name="offset">Offset in the byte array to test.</param> 
/// <returns>The amount of extra bytes to skip ahead for the next read, or -1 if the byte sequence wasn't valid UTF-8</returns> 
public static Int32 TestUtf8(Byte[] binFile, Int32 offset) 
{ 
    Byte current = binFile[offset]; 
    if ((current & 0x80) == 0) 
     return 0; // valid 7-bit ascii. Added length is 0 bytes. 
    else 
    { 
     Int32 len = binFile.Length; 
     Int32 fullmask = 0xC0; 
     Int32 testmask = 0; 
     for (Int32 addedlength = 1; addedlength < 6; addedlength++) 
     { 
      // This code adds shifted bits to get the desired full mask. 
      // If the full mask is [111]0 0000, then test mask will be [110]0 0000. Since this is 
      // effectively always the previous step in the iteration I just store it each time. 
      testmask = fullmask; 
      fullmask += (0x40 >> addedlength); 
      // Test bit mask for this level 
      if ((current & fullmask) == testmask) 
      { 
       // End of file. Might be cut off, but either way, deemed invalid. 
       if (offset + addedlength >= len) 
        return -1; 
       else 
       { 
        // Lookahead. Pattern of any following bytes is always 10xxxxxx 
        for (Int32 i = 1; i <= addedlength; i++) 
        { 
         // If it does not match the pattern for an added byte, it is deemed invalid. 
         if ((binFile[offset + i] & 0xC0) != 0x80) 
          return -1; 
        } 
        return addedlength; 
       } 
      } 
     } 
     // Value is greater than the start of a 6-byte utf8 sequence. Deemed invalid. 
     return -1; 
    } 
} 
+0

Además, no existe la última instrucción 'else' después de' if ((current & 0xE0) == 0xC0) {...} else if ((current & 0xF0) == 0xE0) {...} else if ((actual & 0xF0) == 0xE0) {...} else if ((actual & 0xF8) == 0xF0) {...} '. Supongo que el caso 'else' sería inválido utf8:' isUtf8Valid = false; '. ¿Lo harías? – hal

+0

@hal Ah, cierto ... Desde que actualicé mi propio código con un sistema más general (y más avanzado) que utiliza un bucle que sube a 3, pero que técnicamente puede cambiarse para seguir el bucle (las especificaciones son un poco confusas en eso, es posible expandir UTF-8 hasta 6 bytes añadidos, creo, pero solo 3 se usan en las implementaciones actuales), así que no actualicé este código. – Nyerguds

+0

@hal Lo actualicé a mi nueva solución. El principio sigue siendo el mismo, pero las máscaras de bits se crean y se comprueban en un bucle en lugar de escribirlas explícitamente en el código. – Nyerguds

Cuestiones relacionadas