AliaSQL.Core.FileSystem.GetEncoding C# (CSharp) Method

GetEncoding() private static method

Determines a text file's encoding by analyzing its byte order mark (BOM) Defaults to ASCII when detection of the text file's endianness fails. Function originally from http://stackoverflow.com/questions/3825390/effective-way-to-find-any-files-encoding
private static GetEncoding ( string filename ) : Encoding
filename string The text file to analyze.
return System.Text.Encoding
        private static Encoding GetEncoding(string filename)
        {
            // Read the BOM
            var bom = new byte[4];
            using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                file.Read(bom, 0, 4);
            }

            // Analyze the BOM
            if (bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0x76) return Encoding.UTF7;
            if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) return Encoding.UTF8;
            if (bom[0] == 0xff && bom[1] == 0xfe) return Encoding.Unicode; //UTF-16LE
            if (bom[0] == 0xfe && bom[1] == 0xff) return Encoding.BigEndianUnicode; //UTF-16BE
            if (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff) return Encoding.UTF32;

            return Encoding.ASCII;
        }