How to Get a File's Encoding with C#






3.39/5 (9 votes)
This article describes how to get a file's encoding with C#
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.
/// <summary
/// Get File's Encoding
/// </summary>
/// <param name="filename">The path to the file
private static Encoding GetEncoding(string filename)
{
// This is a direct quote from MSDN:
// The CurrentEncoding value can be different after the first
// call to any Read method of StreamReader, since encoding
// autodetection is not done until the first call to a Read method.
using (var reader = new StreamReader(filename, Encoding.Default, true))
{
if (reader.Peek() >= 0) // you need this!
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!