begin process at 2012 02 11 18:27:28
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Fichiers / Disque

 > C# - FONCTION PERMETTANT D'OBTENIR L'ENCODAGE D'UN FICHIER TEXTE

C# - FONCTION PERMETTANT D'OBTENIR L'ENCODAGE D'UN FICHIER TEXTE


 Information sur la source

Note :
9,25 / 10 - par 4 personnes
9,25 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10
Catégorie :Fichiers / Disque Source .NET ( DotNet ) Classé sous :encoding, text, encodage Niveau :Initié Date de création :20/01/2006 Vu :22 850

Auteur : fabrice69

Ecrire un message privé
Site perso
Ce membre participe au partage de revenus publicitaires
Commentaire sur cette source (3)
Ajouter un commentaire et/ou une note


 Description

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

  • 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;
  • }
  • ....
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


 Sources du même auteur

Source avec Zip Source avec une capture Source .NET (Dotnet) C# - CONTROL END POINTS SQL SERVER 2005
Source avec Zip Source avec une capture Source .NET (Dotnet) C# - CHECK MODE COMPILATION
Source .NET (Dotnet) C# - CONNAÎTRE LE MODE DE COMPILATION UTILISÉ
Source .NET (Dotnet) C# - OBTENIR SI LE FICHIER EST EN UTF8 OU ANSI
Source avec Zip Source avec une capture Source .NET (Dotnet) C# - CHARGER UN FICHIER TEXTE EN CHANGEANT LE PARAMÈTRE D'EN...

 Sources de la même categorie

Source avec Zip Source avec une capture Source .NET (Dotnet) EXPLORATEUR DE DOSSIERS ET FICHIERS par Yanith
Source avec Zip Source avec une capture Source .NET (Dotnet) ZIP-UNZIP AVEC SHARPZIPLIB par buno
Source avec Zip Source .NET (Dotnet) SUPER COPIER par casseur
Source .NET (Dotnet) SERIALIZATION/DESERIALIZATION COMPLÈTE DE CLASSES par DedeSurf
Source avec Zip CONVERSION DE FICHIERS FORTRAN 77 EN FORTRAN 95 par deadhand

 Sources en rapport avec celle ci

Source avec Zip Source avec une capture Source .NET (Dotnet) EDITEUR DE TEXT NOTE PAD par chouatmohamed
Source avec Zip Source avec une capture Source .NET (Dotnet) [WPF] RICH TEXT FORMAT par MasterShadows
Source avec Zip Source avec une capture Source .NET (Dotnet) PANEL IRC AVEC MARGE DEPLACABLE ET BACKGROUND IMAGE par yohan49
Source avec Zip Source avec une capture Source .NET (Dotnet) RICHTEXTBOX NUMÉROTÉ (NUMÉROS DE LIGNES) par jray
Source avec Zip Source avec une capture Source .NET (Dotnet) C# - CHARGER UN FICHIER TEXTE EN CHANGEANT LE PARAMÈTRE D'EN... par fabrice69

Commentaires et avis

Commentaire de rynobouru le 24/05/2006 14:49:20

Merci pour ce code et pour le lien, très bon code qui a marché du premier dans mon projet.
Bravo

Commentaire de yoannd le 09/10/2007 15:12:41 8/10

Très bon code, mais si je ne m'abuse, il manque la fermeture de fichier.

Commentaire de fabrice69 le 09/10/2007 17:16:14 administrateur CS

Effectivement, mais ce code est tout à fait perfectible :)
Fabrice

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

Problème encoding utf8... [ par PeTeRsLaStAr ] Salutations, amis du C# :) (ou la... faut que j'arrête WOW, ça me réussit pas...)Je souhaiterais écrire un fichier (suite à un flux de caractères) de encoding [ par SuperTonic ] Bonjour à tous.J'ai un petit problème que je ne parviens pas à résoudre, malgré mes recherches sur ce site. Je suis sûr d'avoir un début de réponse, m Envoi trame sur liaison série RS 232 [ par arnaud malabeux ] Bonjour à tous Voila mon problème mon code: Byte AdresseMode = 127; Byte LongueurTrame = 128; Byte Rez = 129; port série et séparaton des données [ par moussstiqu3 ] Bonjour, je ne sais pas trop ou poster ce message. Voila mon problème. J'utilise un port série avec visual studio 2010, pour un projet,je reçois de probléme d'authentification en c# [ par theangelofwaxiscomming ] bonjour , je suis débutant en c# , mon problème est que j'ai un form d'authentification (Form3 ) qui permet de s'authentifier avant d'accéder a l'appl TABLEAU [ par facbest ] Bonjour, mon code: done = new string[]{A = "8",B = "1",C = "4",D = "2",E ="6",F = "8",G ="2",H = "8",I ="4",J ="1",K ="7", authentification [ par mustafaBM ] j'essaye d'établir le code c# correspondant à un formulaire d'authentification simple qui contient 2 champs UserName et Password,et même si les ID de Fichier dans ressource [ par facbest ] Bonjour, J'ai créé un fichier Compars.txt dans ressource et je voudrais pouvoir y lire et y écrire. Mon code: _form10 = new Licence(this); Client à la fois serveur. [ par matad0r ] Salut ! Voilà, aujourd'hui je travaille sur un projet. Il y a un client qui envoie des données au serveur et le serveur lui réponds mais aussi envoie utilisé outlook dans un module d'envoi de mail sans que celui-ci soit lancé [ par michelios ] Bonjour, je développe un module permettant d'envoyer un mail avec piece jointe, et ce en utilisant la bibliotheque microsoft.office.interop.outlook.


Nos sponsors


Sondage...

CalendriCode

Février 2012
LMMJVSD
  12345
6789101112
13141516171819
20212223242526
272829    

Consulter la suite du CalendriCode

Photothèque

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 3,401 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales