tags:

views:

144

answers:

1

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#?

+4  A: 

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);
        }
    }
}
Darin Dimitrov
+1, though its worth adding that this is not foolproof; many encodings "look" the same to the simple detection method used. Even the best (which is used by the likes of google that can afford to do a lot of crunching and has lots of data to compare streams with) that will consider different possible meanings of "high" octets, aren't 100% perfect. If at all possible, it's best to convey this information precisely.
Jon Hanna