判断文件编码格式
读取前四个字节判断文件类型
/// <summary> /// 获取文件编码 /// </summary> /// <param name="fs">文件流</param> /// <returns></returns> public static Encoding GetEncoding(FileStream fs) { var bom = new byte[4]; fs.Read(bom, 0, 4); // Analyze the BOM if (bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0x76) { return Encoding.UTF7; } else if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) { return Encoding.UTF8; } else if (bom[0] == 0xff && bom[1] == 0xfe) { return Encoding.Unicode; //UTF-16LE } else if (bom[0] == 0xfe && bom[1] == 0xff) { return Encoding.BigEndianUnicode; //UTF-16BE } else if (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff) { return Encoding.UTF32; } else { return Encoding.ASCII; } }