internal static string BytesToText(byte[] buff, Encoding encoding) { if (buff == null || buff.Length == 0) { return(""); } var detect = new TextEncodingDetect(); encoding = detect.GetEncoding(buff, encoding); if (detect.hasBom) { if (encoding == Encoding.UTF8) { return(encoding.GetString(buff, 3, buff.Length - 3)); } if (encoding == Encoding.Unicode || encoding == Encoding.BigEndianUnicode) { return(encoding.GetString(buff, 2, buff.Length - 2)); } if (encoding == Encoding.UTF32) { return(encoding.GetString(buff, 4, buff.Length - 4)); } } return(encoding.GetString(buff)); }
internal static bool Save(string fileName, string text, bool isAppend, bool writeLogOnError, Encoding encode, int tryCount) { try { //System.Text.Encoding.UTF8 var folder = Path.GetDirectoryName(fileName); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } if (File.Exists(fileName)) { var detect = new TextEncodingDetect(); var detectEncode = detect.GetEncoding(File.ReadAllBytes(fileName), encode); if (detectEncode != Encoding.ASCII) { encode = detectEncode; } } lock (GetLockObj(fileName.Length)) { try { using var writer = new StreamWriter(fileName, isAppend, encode); if (!isAppend && fileName.EndsWith(".txt")) { //写入bom头 } writer.Write(text); } catch (Exception err) { if (tryCount > 0) { tryCount--; Thread.Sleep(500 + (3 - tryCount) * 500); Save(fileName, text, isAppend, writeLogOnError, encode, tryCount); } } } return(true); } catch (Exception err) { if (tryCount != 3) { return(false); } if (writeLogOnError) { } } return(false); }