2009-06-22 7 views
109

Y a-t-il un moyen de déterminer l'encodage d'une chaîne en C#? Dites, j'ai une chaîne de nom de fichier, mais je ne sais pas si elle est codée en Unicode UTF-16 ou l'encodage par défaut du système, comment puis-je savoir?Déterminer le codage d'une chaîne en C#

+0

Vous ne pouvez pas "encoder" en Unicode. Et il n'y a aucun moyen de déterminer automagiquement le codage de _any_ given String, sans aucune autre information préalable. – NicDumZ

+0

"Vous ne pouvez pas" encoder "en Unicode" - si nous interprétons Unicode comme UTF-16 (ou tout autre UTF * spécifique), alors c'est une façon parfaitement valide d'écrire des points de code comme une séquence d'octets. –

+1

comment pouvez-vous écrire de telles approximations? UTF-16 est l'un des moyens possibles pour * encoder * les données Unicode. Vous ne pouvez pas "encoder Unicode"; Unicode n'est pas UTF- *; et UTF- * n'est pas Unicode. Désolé, mais si nous continuons à écrire de telles approximations, comment les comportements liés à Unicode changeront-ils? Les débutants seront toujours confus par le sombre monstre Unicode et les choses ne changeront jamais. Soyons précis. – NicDumZ

Répondre

28

Découvrez Utf8Checker c'est une classe simple qui fait exactement cela en code managé pur. Remarque: comme déjà indiqué, "déterminer le codage" n'a de sens que pour les flux d'octets. Si vous avez une chaîne, elle est déjà codée par quelqu'un qui connaissait ou devinait l'encodage pour obtenir la chaîne en premier lieu.

+0

Si la chaîne est un décodage incorrect fait avec un simplement 8- Encoder et vous avez l'Encodage utilisé pour le décoder, vous pouvez toujours récupérer les octets sans aucune corruption, cependant. – Nyerguds

29

Cela dépend de l'origine de la chaîne. Une chaîne .NET est Unicode (UTF-16). La seule façon dont il pourrait être différent si vous, disons, lire les données d'une base de données dans un tableau d'octets.

Cet article CodeProject pourrait intéresser: Detect Encoding for in- and outgoing text

Jon Skeet Strings in C# and .NET est une excellente explication de chaînes .NET.

+0

Il est venu d'une application C++ non-Unicode .. L'article CodeProject semble un peu trop complexe, mais il semble faire ce que je veux faire .. Merci .. – krebstar

11

Une autre option, très tardive, désolé:

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

Ce petit C# classe -seulement utilise BOMS si elle est présente, essaie de détecter automatiquement les encodages possibles unicode autrement, et retombe si aucun des les encodages Unicode est possible ou probable. Il semble que UTF8Checker référencé ci-dessus fasse quelque chose de similaire, mais je pense que c'est un peu plus large - au lieu de simplement UTF8, il vérifie également d'autres codages Unicode possibles (UTF-16 LE ou BE) qui pourraient manquer un Nomenclature

Espérons que cela aide quelqu'un!

+0

Assez gentil code, il a résolu mon problème de détection d'encodage :) –

14

Je sais que cela est un peu en retard - mais pour être clair:

Une chaîne n'a pas vraiment l'encodage ... dans .NET l'une chaîne est une collection d'objets char. Essentiellement, si c'est une chaîne, elle a déjà été décodée.

Cependant, si vous lisez le contenu d'un fichier, qui est constitué d'octets, et que vous souhaitez le convertir en chaîne, le codage du fichier doit être utilisé.

.NET inclut des classes de codage et de décodage pour: ASCII, UTF7, UTF8, UTF32 et plus.

La plupart de ces codages contiennent certaines marques d'ordre d'octet qui peuvent être utilisées pour distinguer quel type de codage a été utilisé.

La classe .NET System.IO.StreamReader est capable de déterminer le codage utilisé dans un flux, en lisant ces marques d'octets;

Voici un exemple:

/// <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

Cela ne fonctionnera pas pour détecter UTF 16 sans la nomenclature. Elle ne retombera pas non plus sur la page de codes par défaut locale de l'utilisateur si elle ne détecte aucun encodage Unicode. Vous pouvez corriger ce dernier en ajoutant 'Encoding.Default' en tant que paramètre StreamReader, mais le code ne détectera pas UTF8 sans la nomenclature. –

+1

@DanW: UTF-16 sans nomenclature est-il jamais fait, cependant? Je n'utiliserais jamais ça; ça va être un désastre pour ouvrir à peu près n'importe quoi. – Nyerguds

42

Le code ci-dessous présente les caractéristiques suivantes:

  1. détection ou la détection de tentative de UTF-7, UTF-8/16/32 (BOM, no bom, little & big endian)
  2. Retourne à la page de codes par défaut locale si aucun codage Unicode n'a été trouvé.
  3. Détecte (avec une probabilité élevée) les fichiers unicode avec la signature/nomenclature manquante
  4. Recherche charset = xyz et encoding = xyz dans le fichier pour aider à déterminer le codage.
  5. Pour enregistrer le traitement, vous pouvez "goûter" le fichier (nombre d'octets définissable).
  6. Le fichier texte codé et décodé est renvoyé.
  7. solution pour l'efficacité

Purement base d'octet Comme d'autres l'ont dit, aucune solution ne peut être parfait (et certainement on ne peut pas facilement faire la différence entre les différents codages ASCII étendus 8 bits utilisés dans le monde), mais nous pouvons obtenir « assez bonne », surtout si le développeur présente également à l'utilisateur une liste des encodages alternatives comme indiqué ici: What is the most common encoding of each language?

une liste complète des codages peut être trouvée en utilisant 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

Cela fonctionne pour les fichiers .eml cyrillique (et probablement tous les autres) (à partir de l'en-tête charset du courrier) –

+0

Merci beaucoup! – supertopi

+0

UTF-7 ne peut pas être décodé si naïvement, en fait; son préambule complet est plus long et comprend deux bits du premier caractère. Le système .Net semble n'avoir aucun support pour le système de préambule de l'UTF7. – Nyerguds

5

Ma solution consiste à utiliser des éléments intégrés avec certaines solutions de repli.

J'ai choisi la stratégie d'une réponse à une autre question similaire sur stackoverflow mais je ne la trouve pas maintenant.

Il vérifie d'abord la nomenclature à l'aide de la logique intégrée dans StreamReader. S'il existe une nomenclature, l'encodage sera autre chose que Encoding.Default et nous devrions nous fier à ce résultat.

Sinon, il vérifie si la séquence d'octets est une séquence UTF-8 valide. si c'est le cas, il devinera UTF-8 comme encodage, et sinon, encore une fois, le codage ASCII par défaut sera le résultat.

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

Note: ce fut une expérience pour voir comment encodage UTF-8 a travaillé en interne. The solution offered by vilicvane, pour utiliser un objet UTF8Encoding qui est initialisé pour lancer une exception lors d'un échec de décodage, est beaucoup plus simple et fait essentiellement la même chose.


j'ai écrit ce morceau de code pour différencier entre UTF-8 et Windows 1252. Il ne devrait cependant pas être utilisé pour des fichiers texte gigantesques, car il charge tout le contenu en mémoire et l'analyse complètement. Je l'ai utilisé pour les fichiers de sous-titres .srt, juste pour pouvoir les sauvegarder dans l'encodage dans lequel ils ont été chargés.

Le codage donné à la fonction en tant que ref doit être le codage de secours de 8 bits à utiliser dans le cas où le fichier est détecté comme n'étant pas valide UTF-8; généralement, sur les systèmes Windows, ce sera Windows-1252.Cela ne fait rien de fantaisiste comme vérifier les gammes ascii valides actuelles, et ne détecte pas UTF-16, même sur une marque d'ordre des octets.

La théorie derrière la détection de bits peuvent être trouvés ici: https://ianthehenry.com/2015/1/17/decoding-utf-8/

Fondamentalement, la gamme de bits du premier octet détermine le nombre après font partie de l'entité UTF-8. Ces octets après sont toujours dans la même gamme 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

Il n'y a pas de dernière instruction 'else' après' if ((current & 0xE0) == 0xC0) {...} else si ((current & 0xF0) == 0xE0) {...} else if ((current & 0xF0) == 0xE0) {...} sinon if ((current & 0xF8) == 0xF0) {...} '. Je suppose que le cas 'else' serait invalide utf8:' isUtf8Valid = false; '. Voudriez-vous? – hal

+0

@hal Ah, vrai ... Depuis, j'ai mis à jour mon propre code avec un système plus général (et plus avancé) qui utilise une boucle allant jusqu'à 3 mais peut techniquement être changé en boucle (les spécifications sont un peu floues cela, il est possible de développer UTF-8 jusqu'à 6 octets ajoutés je pense, mais seulement 3 sont utilisés dans les implémentations actuelles), donc je n'ai pas mis à jour ce code. – Nyerguds

+0

@hal Mise à jour à ma nouvelle solution. Le principe reste le même, mais les masques de bits sont créés et vérifiés dans une boucle plutôt que tous explicitement écrits dans le code. – Nyerguds

Questions connexes