Introduction
This tip describes how to get a file's encoding with C#.
Background
For some reason, it took me a while to figure it out. All the forums and discussions I found did not have the exact correct way (meaning when I tried to use them, I got wrong results). Although some came very close...
Using the Code
Simply copy paste.
private static Encoding GetEncoding(string filename)
{
using (var reader = new StreamReader(filename, Encoding.Default, true))
{
if (reader.Peek() >= 0)
reader.Read();
return reader.CurrentEncoding;
}
}
Points of Interest
The key to making it work was hidden in the remarks section in MSDN: only after performing a read, we will have the correct CurrentEncoding
value.
I hope this helps!