public static Encoding FindBestEncodingForFile(string file) { Encoding targetEncoding; Byte[] fileContent; fileContent = System.IO.File.ReadAllBytes(file); targetEncoding = EncodingTools.DetectInputCodepage(fileContent); return(targetEncoding); }
public static string AutoDecodeString(string SourceString) { if ((SourceString == null) || (SourceString.Length == 0)) { return(String.Empty); } using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { Encoding srcEnc = EncodingTools.GetMostEfficientEncoding(SourceString); //MessageBox.Show(srcEnc.EncodingName); byte[] encoded = srcEnc.GetBytes(SourceString); // preamble? byte[] preamble = srcEnc.GetPreamble(); // Make sure a preamble was returned // and is large enough to containa BOM. if (preamble.Length >= 2) { ms.Write(preamble, 0, preamble.Length); } ms.Write(encoded, 0, encoded.Length); ms.Position = 0; Encoding targetEncoding; byte[] rawData = ms.ToArray(); try { targetEncoding = EncodingTools.DetectInputCodepage(rawData); } catch (System.Runtime.InteropServices.COMException) { targetEncoding = Encoding.GetEncoding(MyPreferedEncodingCodePage); } return(targetEncoding.GetString(rawData)); } }