// 编码批量转换 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法(net48 自带 csc 可编译) // 功能:把一堆 txt/csv/md/代码文件从 GBK 转成 UTF-8(或反过来),自动识别原编码 // 边界:输出到「编码转换」子文件夹,原文件绝不动;识别不了的(二进制)直接跳过并写明 // 原理:先看 BOM,再做 UTF-8 严格解码校验,最后按 GBK 双字节规则校验;三者都不成立才判未知 using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public class EncOps { public const string TargetUtf8 = "UTF-8(无 BOM)"; public const string TargetUtf8Bom = "UTF-8(带 BOM)"; public const string TargetGbk = "GBK(简体中文老系统)"; public const string TargetUtf16 = "UTF-16 LE(带 BOM)"; public static string[] Targets() { return new string[] { TargetUtf8, TargetUtf8Bom, TargetGbk, TargetUtf16 }; } public class DetectResult { public string Name; // ASCII / UTF-8 / UTF-16 LE / GBK / 未知 public bool HasBom; public int BomLen; public string Note = ""; } public static Encoding Gbk() { return Encoding.GetEncoding(936); } /* UTF-16 LE 无 BOM 的粗判:隔一个字节就有一个 0 */ static bool LooksUtf16(byte[] d, bool little) { if (d.Length < 4 || (d.Length % 2) != 0) return false; int zero = 0, total = d.Length / 2; for (int i = 0; i < d.Length; i += 2) { int z = little ? d[i + 1] : d[i]; if (z == 0) zero++; } return zero >= total * 3 / 4; } /* GBK 双字节规则:首字节 0x81-0xFE,次字节 0x40-0xFE 且不等于 0x7F */ static bool IsGbk(byte[] d) { int i = 0, pairs = 0; while (i < d.Length) { byte b = d[i]; if (b < 0x80) { i++; continue; } if (b == 0x80 || b == 0xFF) return false; if (i + 1 >= d.Length) return false; byte b2 = d[i + 1]; if (b2 < 0x40 || b2 == 0x7F || b2 == 0xFF) return false; pairs++; i += 2; } return pairs > 0; } public static DetectResult Detect(byte[] d) { DetectResult r = new DetectResult(); if (d == null || d.Length == 0) { r.Name = "空文件"; r.Note = "0 字节,直接跳过"; return r; } if (d.Length >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF) { r.Name = "UTF-8"; r.HasBom = true; r.BomLen = 3; return r; } if (d.Length >= 2 && d[0] == 0xFF && d[1] == 0xFE) { r.Name = "UTF-16 LE"; r.HasBom = true; r.BomLen = 2; return r; } if (d.Length >= 2 && d[0] == 0xFE && d[1] == 0xFF) { r.Name = "UTF-16 BE"; r.HasBom = true; r.BomLen = 2; return r; } if (LooksUtf16(d, true)) { r.Name = "UTF-16 LE"; r.Note = "无 BOM,按字节规律判断"; return r; } if (LooksUtf16(d, false)) { r.Name = "UTF-16 BE"; r.Note = "无 BOM,按字节规律判断"; return r; } // 文本文件不会有 0 字节(UTF-16 上面已经排掉了):先拦二进制, // 否则随机字节很容易凑巧符合 GBK 双字节规则,被当成「能转的文本」 for (int i = 0; i < d.Length; i++) { if (d[i] == 0) { r.Name = "未知"; r.Note = "含 0 字节,像是二进制文件(exe/图片/压缩包)"; return r; } } // UTF-8 严格解码:有非法序列会抛异常 try { new UTF8Encoding(false, true).GetString(d); bool ascii = true; for (int i = 0; i < d.Length; i++) { if (d[i] >= 0x80) { ascii = false; break; } } r.Name = ascii ? "ASCII" : "UTF-8"; if (ascii) r.Note = "纯英文数字,转 UTF-8 与 GBK 结果一样"; return r; } catch (ArgumentException) { } if (IsGbk(d)) { r.Name = "GBK"; return r; } r.Name = "未知"; r.Note = "既不是合法 UTF-8,也不符合 GBK 双字节规则"; return r; } public static string Decode(byte[] d, DetectResult det) { if (det == null) return null; Encoding enc; if (det.Name == "GBK") enc = Gbk(); else if (det.Name == "UTF-16 LE") enc = new UnicodeEncoding(false, false); else if (det.Name == "UTF-16 BE") enc = new UnicodeEncoding(true, false); else if (det.Name == "UTF-8" || det.Name == "ASCII") enc = new UTF8Encoding(false, false); else return null; string s = enc.GetString(d); if (s.Length > 0 && s[0] == '\uFEFF') s = s.Substring(1); return s; } public static byte[] Encode(string text, string target) { if (target == TargetUtf8) return new UTF8Encoding(false).GetBytes(text); if (target == TargetUtf8Bom) { byte[] body = new UTF8Encoding(false).GetBytes(text); byte[] all = new byte[body.Length + 3]; all[0] = 0xEF; all[1] = 0xBB; all[2] = 0xBF; Array.Copy(body, 0, all, 3, body.Length); return all; } if (target == TargetGbk) return Gbk().GetBytes(text); if (target == TargetUtf16) return new UnicodeEncoding(false, true).GetBytes(text); throw new ArgumentException("不认识的目标编码:" + target); } public static int CountReplacement(string s) { int n = 0; for (int i = 0; i < s.Length; i++) if (s[i] == '\uFFFD') n++; return n; } /* 只把这些扩展名当文本;用户要求「全部文件」时不看这个表 */ public static bool IsTextName(string file) { string e = Path.GetExtension(file).ToLowerInvariant(); string[] exts = new string[] { ".txt", ".csv", ".tsv", ".md", ".markdown", ".json", ".xml", ".html", ".htm", ".css", ".js", ".ini", ".log", ".sql", ".yml", ".yaml", ".bat", ".cmd", ".ps1", ".cs", ".java", ".php", ".py", ".srt", ".vtt", ".properties", ".conf", ".cfg", ".reg", ".asp", ".jsp", ".vue", ".go", ".rb", ".sh" }; foreach (string x in exts) if (x == e) return true; return false; } public class Row { public string File; public string Detected; public string Size; public string Result; public string Note; } public class BatchResult { public List Rows = new List(); public int Converted; public int Copied; public int Skipped; public string OutDir; } public static BatchResult Scan(string folder, bool recursive, bool onlyText) { if (!Directory.Exists(folder)) throw new IOException("目录不存在:" + folder); BatchResult r = new BatchResult(); string[] files = Directory.GetFiles(folder, "*.*", recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); foreach (string f in files) { if (onlyText && !IsTextName(f)) continue; try { byte[] d = File.ReadAllBytes(f); DetectResult det = Detect(d); Row row = new Row(); row.File = RelName(folder, f); row.Detected = det.Name + (det.HasBom ? "(带 BOM)" : ""); row.Size = SizeText(d.Length); row.Result = ""; row.Note = det.Note; r.Rows.Add(row); } catch (Exception ex) { Row row = new Row(); row.File = RelName(folder, f); row.Detected = "读不出来"; row.Size = ""; row.Result = ""; row.Note = ex.Message; r.Rows.Add(row); } } return r; } public static BatchResult Batch(string folder, string target, bool recursive, bool onlyText) { if (!Directory.Exists(folder)) throw new IOException("目录不存在:" + folder); BatchResult r = new BatchResult(); string outDir = Path.Combine(folder, "编码转换"); r.OutDir = outDir; Directory.CreateDirectory(outDir); string outPrefix = outDir.TrimEnd('\\') + "\\"; string[] files = Directory.GetFiles(folder, "*.*", recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); foreach (string f in files) { // 输出目录就在源目录里,递归时必须跳过,否则第二次跑会把自己的产物再转一遍 if (f.StartsWith(outPrefix, StringComparison.OrdinalIgnoreCase)) continue; if (onlyText && !IsTextName(f)) continue; Row row = new Row(); row.File = RelName(folder, f); try { byte[] d = File.ReadAllBytes(f); DetectResult det = Detect(d); row.Detected = det.Name + (det.HasBom ? "(带 BOM)" : ""); row.Size = SizeText(d.Length); string text = Decode(d, det); if (text == null) { row.Result = "跳过"; row.Note = det.Note.Length > 0 ? det.Note : "不是能识别的文本编码"; r.Skipped++; r.Rows.Add(row); continue; } string rel = RelName(folder, f); string outPath = Path.Combine(outDir, rel); Directory.CreateDirectory(Path.GetDirectoryName(outPath)); bool same = IsSameEncoding(det, target); if (same) { File.Copy(f, outPath, true); row.Result = "原样复制"; row.Note = "已经是目标编码"; r.Copied++; } else { byte[] enc = Encode(text, target); File.WriteAllBytes(outPath, enc); int bad = CountReplacement(text); row.Result = "已转换"; row.Note = bad > 0 ? "有 " + bad + " 个字符识别失败(原编码可能判断错了)" : "原编码 " + det.Name + " → " + target; r.Converted++; } r.Rows.Add(row); } catch (Exception ex) { row.Result = "失败"; row.Note = ex.Message; r.Skipped++; r.Rows.Add(row); } } return r; } static bool IsSameEncoding(DetectResult det, string target) { if (target == TargetUtf8) return det.Name == "UTF-8" && !det.HasBom; if (target == TargetUtf8Bom) return det.Name == "UTF-8" && det.HasBom; if (target == TargetGbk) return det.Name == "GBK"; if (target == TargetUtf16) return det.Name == "UTF-16 LE" && det.HasBom; return false; } public static string RelName(string root, string file) { string r = file.Substring(root.TrimEnd('\\').Length).TrimStart('\\'); return r; } public static string SizeText(long n) { if (n < 1024) return n + " B"; if (n < 1024 * 1024) return (n / 1024.0).ToString("0.0") + " KB"; return (n / 1048576.0).ToString("0.0") + " MB"; } } public class EncConvForm : Form { private TextBox txtDir; private Button btnPick; private ComboBox cbTarget; private CheckBox chkRecursive; private CheckBox chkOnlyText; private Button btnScan; private Button btnRun; private Button btnOpen; private ListView lv; private Label lblStatus; private ProgressBar progress; private BackgroundWorker worker; public EncConvForm() { InitUi(); worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler(WorkerDoWork); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(WorkerDone); } private void InitUi() { this.Text = "编码批量转换 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 9.5f); this.BackColor = Color.White; this.ForeColor = Color.FromArgb(34, 40, 36); this.ClientSize = new Size(820, 540); this.MinimumSize = new Size(720, 460); this.AllowDrop = true; this.DragEnter += new DragEventHandler(FormDragEnter); this.DragDrop += new DragEventHandler(FormDragDrop); int x = 20, y = 16; Label lblTitle = new Label(); lblTitle.Text = "GBK 乱码文件一键转 UTF-8(也能反向转):自动识别原编码,输出到「编码转换」文件夹"; lblTitle.Location = new Point(x, y); lblTitle.AutoSize = true; lblTitle.ForeColor = Color.FromArgb(120, 130, 124); this.Controls.Add(lblTitle); y += 30; txtDir = new TextBox(); txtDir.Location = new Point(x, y); txtDir.Size = new Size(620, 26); this.Controls.Add(txtDir); btnPick = new Button(); btnPick.Text = "浏览…"; btnPick.Location = new Point(652, y - 1); btnPick.Size = new Size(90, 28); btnPick.Click += new EventHandler(PickClick); this.Controls.Add(btnPick); y += 40; Label lbT = new Label(); lbT.Text = "转成"; lbT.Location = new Point(x, y + 4); lbT.AutoSize = true; this.Controls.Add(lbT); cbTarget = new ComboBox(); cbTarget.DropDownStyle = ComboBoxStyle.DropDownList; cbTarget.Location = new Point(x + 44, y); cbTarget.Size = new Size(230, 26); cbTarget.Items.AddRange(EncOps.Targets()); cbTarget.SelectedIndex = 0; this.Controls.Add(cbTarget); chkRecursive = new CheckBox(); chkRecursive.Text = "包含子文件夹"; chkRecursive.Location = new Point(x + 292, y + 3); chkRecursive.AutoSize = true; chkRecursive.Checked = true; this.Controls.Add(chkRecursive); chkOnlyText = new CheckBox(); chkOnlyText.Text = "只处理文本类扩展名(推荐)"; chkOnlyText.Location = new Point(x + 420, y + 3); chkOnlyText.AutoSize = true; chkOnlyText.Checked = true; this.Controls.Add(chkOnlyText); y += 40; btnScan = new Button(); btnScan.Text = "先扫描看看"; btnScan.Location = new Point(x, y); btnScan.Size = new Size(120, 34); btnScan.Click += new EventHandler(ScanClick); this.Controls.Add(btnScan); btnRun = new Button(); btnRun.Text = "开始转换"; btnRun.Location = new Point(x + 132, y); btnRun.Size = new Size(130, 34); btnRun.BackColor = Color.FromArgb(0, 145, 88); btnRun.ForeColor = Color.White; btnRun.FlatStyle = FlatStyle.Flat; btnRun.Click += new EventHandler(RunClick); this.Controls.Add(btnRun); btnOpen = new Button(); btnOpen.Text = "打开输出文件夹"; btnOpen.Location = new Point(x + 274, y); btnOpen.Size = new Size(130, 34); btnOpen.Click += new EventHandler(OpenClick); this.Controls.Add(btnOpen); progress = new ProgressBar(); progress.Location = new Point(420, y + 6); progress.Size = new Size(322, 20); progress.Style = ProgressBarStyle.Marquee; progress.MarqueeAnimationSpeed = 40; progress.Visible = false; this.Controls.Add(progress); y += 48; lblStatus = new Label(); lblStatus.Text = "把文件夹拖到窗口上。扫描只读文件、不改任何东西;转换输出的原文件一个字都不动。"; lblStatus.Location = new Point(x, y); lblStatus.AutoSize = true; lblStatus.ForeColor = Color.FromArgb(120, 130, 124); this.Controls.Add(lblStatus); y += 28; lv = new ListView(); lv.View = View.Details; lv.FullRowSelect = true; lv.Location = new Point(x, y); lv.Size = new Size(780, 340); lv.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; lv.Columns.Add("文件", 320); lv.Columns.Add("识别为", 140); lv.Columns.Add("大小", 70); lv.Columns.Add("结果", 80); lv.Columns.Add("备注", 200); this.Controls.Add(lv); } private void PickClick(object sender, EventArgs e) { FolderBrowserDialog dlg = new FolderBrowserDialog(); if (Directory.Exists(txtDir.Text)) dlg.SelectedPath = txtDir.Text; if (dlg.ShowDialog(this) == DialogResult.OK) txtDir.Text = dlg.SelectedPath; } private void FormDragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; } private void FormDragDrop(object sender, DragEventArgs e) { string[] paths = (string[])e.Data.GetData(DataFormats.FileDrop); if (paths.Length > 0 && Directory.Exists(paths[0])) txtDir.Text = paths[0]; } private string Dir() { return (txtDir.Text ?? "").Trim(); } private void ScanClick(object sender, EventArgs e) { string dir = Dir(); if (dir.Length == 0 || !Directory.Exists(dir)) { lblStatus.ForeColor = Color.FromArgb(200, 50, 50); lblStatus.Text = "先选一个存在的文件夹。"; return; } try { EncOps.BatchResult r = EncOps.Scan(dir, chkRecursive.Checked, chkOnlyText.Checked); Fill(r); lblStatus.ForeColor = Color.FromArgb(0, 145, 88); lblStatus.Text = "扫描了 " + r.Rows.Count + " 个文件(只读,没动任何文件)。确认无误再点「开始转换」。"; } catch (Exception ex) { lblStatus.ForeColor = Color.FromArgb(200, 50, 50); lblStatus.Text = "扫描失败:" + ex.Message; } } private void RunClick(object sender, EventArgs e) { string dir = Dir(); if (dir.Length == 0 || !Directory.Exists(dir)) { lblStatus.ForeColor = Color.FromArgb(200, 50, 50); lblStatus.Text = "先选一个存在的文件夹。"; return; } btnRun.Enabled = false; btnScan.Enabled = false; progress.Visible = true; string[] arg = new string[] { dir, (string)cbTarget.SelectedItem, chkRecursive.Checked ? "1" : "0", chkOnlyText.Checked ? "1" : "0" }; worker.RunWorkerAsync(arg); } private void WorkerDoWork(object sender, DoWorkEventArgs e) { string[] a = (string[])e.Argument; e.Result = EncOps.Batch(a[0], a[1], a[2] == "1", a[3] == "1"); } private void WorkerDone(object sender, RunWorkerCompletedEventArgs e) { btnRun.Enabled = true; btnScan.Enabled = true; progress.Visible = false; if (e.Error != null) { lblStatus.ForeColor = Color.FromArgb(200, 50, 50); lblStatus.Text = "转换失败:" + e.Error.Message; return; } EncOps.BatchResult r = (EncOps.BatchResult)e.Result; Fill(r); lblStatus.ForeColor = Color.FromArgb(0, 145, 88); lblStatus.Text = "转换 " + r.Converted + " 个,原样复制 " + r.Copied + " 个,跳过 " + r.Skipped + " 个。输出在「编码转换」文件夹,原文件没动。"; } private void Fill(EncOps.BatchResult r) { lv.BeginUpdate(); lv.Items.Clear(); foreach (EncOps.Row row in r.Rows) { ListViewItem li = new ListViewItem(row.File); li.SubItems.Add(row.Detected); li.SubItems.Add(row.Size); li.SubItems.Add(row.Result); li.SubItems.Add(row.Note); if (row.Result == "跳过" || row.Result == "失败") li.ForeColor = Color.FromArgb(190, 90, 40); lv.Items.Add(li); } lv.EndUpdate(); } private void OpenClick(object sender, EventArgs e) { string dir = Path.Combine(Dir(), "编码转换"); if (Directory.Exists(dir)) System.Diagnostics.Process.Start("explorer.exe", "\"" + dir + "\""); else { lblStatus.ForeColor = Color.FromArgb(200, 50, 50); lblStatus.Text = "还没有输出文件夹,先转换一次。"; } } } // ───────────────────────── 自测 ───────────────────────── public static class EncSelfTest { static int _pass, _fail; static List _lines = new List(); static void Check(string name, object got, object want) { bool ok = string.Equals(got == null ? "" : got.ToString(), want == null ? "" : want.ToString()); if (ok) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " got=" + got + " want=" + want); } } const string Sample = "第一行 中文\r\n第二行 English 123\n"; public static int Run(string dir) { _pass = 0; _fail = 0; _lines = new List(); _lines.Add("编码批量转换 自测 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); string baseDir = string.IsNullOrEmpty(dir) ? Path.Combine(Path.GetTempPath(), "gt-enc-" + Guid.NewGuid().ToString("N").Substring(0, 8)) : dir; try { Directory.CreateDirectory(baseDir); Encoding gbk = EncOps.Gbk(); string fGbk = Path.Combine(baseDir, "gbk.txt"); File.WriteAllBytes(fGbk, gbk.GetBytes(Sample)); string fUtf8 = Path.Combine(baseDir, "utf8.txt"); File.WriteAllBytes(fUtf8, new UTF8Encoding(false).GetBytes(Sample)); string fAscii = Path.Combine(baseDir, "ascii.txt"); File.WriteAllText(fAscii, "hello world", new UTF8Encoding(false)); string fBom = Path.Combine(baseDir, "bom.txt"); File.WriteAllText(fBom, Sample, new UTF8Encoding(true)); string f16 = Path.Combine(baseDir, "u16.txt"); File.WriteAllText(f16, Sample, Encoding.Unicode); string fBin = Path.Combine(baseDir, "app.exe"); byte[] bin = new byte[64]; for (int i = 0; i < bin.Length; i++) bin[i] = (byte)(i * 3); File.WriteAllBytes(fBin, bin); Check("GBK 识别", EncOps.Detect(File.ReadAllBytes(fGbk)).Name, "GBK"); Check("UTF-8 识别", EncOps.Detect(File.ReadAllBytes(fUtf8)).Name, "UTF-8"); Check("ASCII 识别", EncOps.Detect(File.ReadAllBytes(fAscii)).Name, "ASCII"); EncOps.DetectResult db = EncOps.Detect(File.ReadAllBytes(fBom)); Check("BOM 识别", db.Name, "UTF-8"); Check("BOM 长度", db.BomLen, 3); Check("UTF-16 识别", EncOps.Detect(File.ReadAllBytes(f16)).Name, "UTF-16 LE"); Check("二进制判未知", EncOps.Detect(bin).Name, "未知"); Check("空文件判空", EncOps.Detect(new byte[0]).Name, "空文件"); // GBK → UTF-8 EncOps.BatchResult r1 = EncOps.Batch(baseDir, EncOps.TargetUtf8, false, true); Check("GBK 文件被转换", r1.Converted >= 3, true); string outGbk = Path.Combine(baseDir, "编码转换", "gbk.txt"); Check("输出文件存在", File.Exists(outGbk), true); byte[] outBytes = File.ReadAllBytes(outGbk); Check("UTF-8 无 BOM", outBytes[0] == 0xEF ? "bom" : "nobom", "nobom"); Check("内容一致(中文没坏)", new UTF8Encoding(false).GetString(outBytes) == Sample, true); // 原文件一个字节都没变 Check("原文件仍是 GBK", EncOps.Detect(File.ReadAllBytes(fGbk)).Name, "GBK"); Check("原文件字节未变", gbk.GetString(File.ReadAllBytes(fGbk)) == Sample, true); // UTF-8 带 BOM 目标 EncOps.BatchResult r2 = EncOps.Batch(baseDir, EncOps.TargetUtf8Bom, false, true); byte[] bomOut = File.ReadAllBytes(Path.Combine(baseDir, "编码转换", "utf8.txt")); Check("加 BOM 成功", bomOut[0] == 0xEF && bomOut[1] == 0xBB && bomOut[2] == 0xBF, true); Check("加 BOM 后正文仍对", new UTF8Encoding(false).GetString(bomOut, 3, bomOut.Length - 3) == Sample, true); Check("已是目标编码的原样复制", r2.Copied >= 1, true); // 反向:UTF-8 → GBK EncOps.BatchResult r3 = EncOps.Batch(baseDir, EncOps.TargetGbk, false, true); byte[] back = File.ReadAllBytes(Path.Combine(baseDir, "编码转换", "utf8.txt")); Check("转回 GBK 识别为 GBK", EncOps.Detect(back).Name, "GBK"); Check("转回 GBK 内容一致", gbk.GetString(back) == Sample, true); Check("UTF-8 源被转换", r3.Converted >= 1, true); // 递归 + 相对路径保留 string sub = Path.Combine(baseDir, "sub"); Directory.CreateDirectory(sub); File.WriteAllBytes(Path.Combine(sub, "inner.txt"), gbk.GetBytes("子目录内容")); EncOps.BatchResult r4 = EncOps.Batch(baseDir, EncOps.TargetUtf8, true, true); Check("子目录结构保留", File.Exists(Path.Combine(baseDir, "编码转换", "sub", "inner.txt")), true); Check("子目录内容正确", File.ReadAllText(Path.Combine(baseDir, "编码转换", "sub", "inner.txt"), new UTF8Encoding(false)) == "子目录内容", true); // 再跑一次不会把输出目录里的产物再转一遍 EncOps.BatchResult r5 = EncOps.Batch(baseDir, EncOps.TargetUtf8, true, true); int dup = 0; foreach (EncOps.Row row in r5.Rows) { if (row.File.StartsWith("编码转换\\") || row.File.StartsWith("编码转换/")) dup++; } Check("不重复处理自己的输出", dup, 0); // 非文本扩展名被过滤 int hasExe = 0; foreach (EncOps.Row row in r5.Rows) if (row.File == "app.exe") hasExe++; Check("exe 被扩展名过滤", hasExe, 0); EncOps.BatchResult r6 = EncOps.Batch(baseDir, EncOps.TargetUtf8, false, false); int exeSkipped = 0; foreach (EncOps.Row row in r6.Rows) if (row.File == "app.exe" && row.Result == "跳过") exeSkipped++; Check("全文件模式跳过二进制", exeSkipped, 1); // 扫描不产生输出 string fresh = Path.Combine(baseDir, "scanonly"); Directory.CreateDirectory(fresh); File.WriteAllBytes(Path.Combine(fresh, "a.txt"), gbk.GetBytes("扫描")); EncOps.Scan(fresh, false, true); Check("扫描不建输出夹", Directory.Exists(Path.Combine(fresh, "编码转换")), false); // 空目录不炸 string emptyDir = Path.Combine(baseDir, "empty"); Directory.CreateDirectory(emptyDir); Check("空目录批量为 0", EncOps.Batch(emptyDir, EncOps.TargetUtf8, false, true).Rows.Count, 0); bool threw = false; try { EncOps.Batch(Path.Combine(baseDir, "nope"), EncOps.TargetUtf8, false, true); } catch { threw = true; } Check("目录不存在抛异常", threw ? "threw" : "silent", "threw"); Check("不含替换符", EncOps.CountReplacement(EncOps.Decode( gbk.GetBytes(Sample), EncOps.Detect(gbk.GetBytes(Sample)))), 0); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } finally { try { Directory.Delete(baseDir, true); } catch { } } _lines.Add(""); _lines.Add(_fail == 0 ? "结果:共 " + (_pass + _fail) + " 项,全部通过 ✓" : "结果:共 " + (_pass + _fail) + " 项,通过 " + _pass + ",失败 " + _fail + " ✗"); string all = string.Join("\r\n", _lines.ToArray()); Console.WriteLine(all); try { File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "selftest-encodeconv.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } static class Program { [STAThread] static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(EncSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new EncConvForm()); } } }