using System; using System.IO; using System.Text; namespace DrillTools { /// /// 钻带/参数文件统一读取入口。 /// 默认按 ANSI/GB2312(code page 936) 解码,等价于历史 `cmd type` 实现的字节透传语义, /// 但不经过命令行,因此路径中的特殊字符(如 `(` `)` `&` `%` `!` `^` `@` 空格)不会影响读取。 /// internal static class AnsiFileReader { private const int Gb2312CodePage = 936; public static string ReadAllText(string filePath) { return ReadAllText(filePath, CreateAnsiEncoding()); } public static string ReadAllText(string filePath, Encoding encoding) { string normalizedPath = ValidateAndNormalizePath(filePath); try { using var stream = new FileStream(normalizedPath, FileMode.Open, FileAccess.Read, FileShare.Read); // detectEncodingFromByteOrderMarks: true 与历史实现保持一致: // 原先经 Process.StandardOutput(StreamReader) 解码,默认会探测 BOM, // 因此带 UTF-8/UTF-16 BOM 的文件解码结果保持不变。 using var reader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true); return reader.ReadToEnd(); } catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) { throw new InvalidOperationException($"读取文件失败:{normalizedPath}({ex.Message})", ex); } } private static string ValidateAndNormalizePath(string filePath) { if (string.IsNullOrWhiteSpace(filePath)) throw new ArgumentException("文件路径不能为空", nameof(filePath)); string normalizedPath = Path.GetFullPath(filePath); if (!File.Exists(normalizedPath)) throw new FileNotFoundException($"文件不存在:{normalizedPath}", normalizedPath); return normalizedPath; } private static Encoding CreateAnsiEncoding() { return Encoding.GetEncoding(Gb2312CodePage); } } }