Skip to content

Instantly share code, notes, and snippets.

@alex6dj
Created February 23, 2018 15:28
Show Gist options
  • Select an option

  • Save alex6dj/3b5128d8f5ba423504256c15b72f6219 to your computer and use it in GitHub Desktop.

Select an option

Save alex6dj/3b5128d8f5ba423504256c15b72f6219 to your computer and use it in GitHub Desktop.
/// From https://www.codeproject.com/Tips/1231324/How-to-Get-a-Files-Encoding-with-Csharp
/// <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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment