C# - fonction permettant d'obtenir l'encodage d'un fichier texte

Contenu du snippet

Dans le cadre d'un développement qui me fournit des fichiers textes sous différents encodages, j'ai développé cette petite fonction permettant de connaître l'encodage courant du fichier voulu.
Cette fonction est inspirée par celle-ci de Heath Stewart :
- http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=469

J'ai d'ailleurs laissé ses commentaires d'origine.

Source / Exemple :

using System.Text;
using System.IO;

....

/// <summary>
/// Permet de tester l'encodage utilisé pour le fichier texte dont le chemin est fourni
/// </summary>
/// <param name="CheminFichier">Chemin du fichier</param>
/// <returns>Encodage du fichier Texte</returns>
private Encoding ObtientENcoding(string CheminFichier)
{
 Encoding enc = null;
 FileStream file = new FileStream(CheminFichier, FileMode.Open, FileAccess.Read, FileShare.Read
 if (file.CanSeek)
 {
  byte[] bom = new byte[4]; // Get the byte-order mark, if there is one
  file.Read(bom, 0, 4);
  if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) // utf-8
  {
   enc = Encoding.UTF8;
  }
  else if ((bom[0] == 0xff && bom[1] == 0xfe) || // ucs-2le, ucs-4le, and ucs-16le
   (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff)) // ucs-4
  {
   enc = Encoding.Unicode;
  }
  else if (bom[0] == 0xfe && bom[1] == 0xff) // utf-16 and ucs-2
  {
   enc = Encoding.BigEndianUnicode;
  }
  else // ANSI, Default
  {
   enc = Encoding.Default;
  }
  // Now reposition the file cursor back to the start of the file
  file.Seek(0, SeekOrigin.Begin);
 }
 else
 {
  // The file cannot be randomly accessed, so you need to decide what to set the default to
  // based on the data provided. If you're expecting data from a lot of older applications,
  // default your encoding to Encoding.ASCII. If you're expecting data from a lot of newer
  // applications, default your encoding to Encoding.Unicode. Also, since binary files are
  // single byte-based, so you will want to use Encoding.ASCII, even though you'll probably
  // never need to use the encoding then since the Encoding classes are really meant to get
  // strings from the byte array that is the file.

  enc = Encoding.Default;
 }
return enc;
}

....

Conclusion :

En espérant que cela vous soit utile.

Bon coding.

Romelard Fabrice

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.