Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto encoding detect in C# [duplicate]

Tags:

c#

.net

encoding

Possible Duplicate:
Determine a string's encoding in C#

Many text editorsr (like Notepad++) can detect encoding of arbitrary file. Can I detect encodoing of file in C#?

like image 847
AndreyAkinshin Avatar asked Sep 19 '10 16:09

AndreyAkinshin


1 Answers

A StreamReader will try to automatically detect the encoding of a file if there's a BOM when trying to read:

public class Program
{
    static void Main(string[] args)
    {
        using (var reader = new StreamReader("foo.txt"))
        {
            // Make sure you read from the file or it won't be able
            // to guess the encoding
            var file = reader.ReadToEnd();
            Console.WriteLine(reader.CurrentEncoding);
        }
    }
}
like image 136
Darin Dimitrov Avatar answered Oct 21 '22 06:10

Darin Dimitrov