// 文本工具 - 绿色工具箱 // C# 5.0 语法,零依赖。功能:GBK/UTF-8/Unicode 编码互转、去空行、去重行、排序、 // 全部替换、大小写、加行号、去 BOM。面向"把一个编码乱的文件修好"这个高频老需求 using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public class TextToolForm : Form { private static readonly Color COL_GREEN = Color.FromArgb(0, 145, 88); private static readonly Color COL_PANEL = Color.FromArgb(245, 249, 246); private static readonly Color COL_GRAY = Color.FromArgb(120, 130, 124); private TextBox txtMain; private ComboBox cmbEnc; private Button btnOpen, btnSave, btnApply; private ComboBox cmbOp; private TextBox txtFind, txtRepl; private Label lblStatus; private string currentFile = ""; private Encoding currentEnc = null; private bool loading = false; // 载入文件时抑制「改编码就重载」的回调,避免自我递归 public TextToolForm() { InitUi(); } 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, 600); this.MinimumSize = new Size(720, 540); this.AllowDrop = true; this.DragEnter += new DragEventHandler(OnDragEnter); this.DragDrop += new DragEventHandler(OnDragDrop); int x = 16, y = 14; btnOpen = MkBtn("打开文件", x, y, 100, false); btnOpen.Click += new EventHandler(OpenClick); Label le = new Label(); le.Text = "编码:"; le.AutoSize = true; le.Location = new Point(x + 112, y + 7); this.Controls.Add(le); cmbEnc = new ComboBox(); cmbEnc.DropDownStyle = ComboBoxStyle.DropDownList; cmbEnc.Items.Add("自动识别"); cmbEnc.Items.Add("UTF-8"); cmbEnc.Items.Add("GBK (中文Windows默认)"); cmbEnc.Items.Add("Unicode (UTF-16LE)"); cmbEnc.SelectedIndex = 0; cmbEnc.Location = new Point(x + 164, y + 3); cmbEnc.Size = new Size(200, 26); cmbEnc.SelectedIndexChanged += new EventHandler(delegate(object s, EventArgs e) { ReloadIfFile(); }); this.Controls.Add(cmbEnc); btnSave = MkBtn("另存为…", 700, y, 104, false); btnSave.Click += new EventHandler(SaveClick); y += 42; Label lo = new Label(); lo.Text = "处理:"; lo.AutoSize = true; lo.Location = new Point(x, y + 5); this.Controls.Add(lo); cmbOp = new ComboBox(); cmbOp.DropDownStyle = ComboBoxStyle.DropDownList; // 选项文案和 TextOps 的动作编号必须一一对应,直接从 OP_NAMES 建,顺序不会漂 foreach (string opName in TextOps.OP_NAMES) cmbOp.Items.Add(opName); cmbOp.SelectedIndex = 0; cmbOp.Location = new Point(x + 52, y + 2); cmbOp.Size = new Size(220, 26); this.Controls.Add(cmbOp); btnApply = MkBtn("应用", x + 286, y - 1, 80, true); btnApply.Click += new EventHandler(ApplyClick); Label lf = new Label(); lf.Text = "查找:"; lf.AutoSize = true; lf.Location = new Point(x + 382, y + 5); this.Controls.Add(lf); txtFind = new TextBox(); txtFind.Location = new Point(x + 426, y + 2); txtFind.Size = new Size(130, 26); this.Controls.Add(txtFind); Label lr = new Label(); lr.Text = "替换:"; lr.AutoSize = true; lr.Location = new Point(x + 564, y + 5); this.Controls.Add(lr); txtRepl = new TextBox(); txtRepl.Location = new Point(x + 608, y + 2); txtRepl.Size = new Size(130, 26); this.Controls.Add(txtRepl); Button btnRepl = MkBtn("执行替换", 752, y - 1, 52, false); btnRepl.Click += new EventHandler(ReplaceClick); y += 42; txtMain = new TextBox(); txtMain.Location = new Point(x, y); txtMain.Size = new Size(788, 470); txtMain.Multiline = true; txtMain.ScrollBars = ScrollBars.Both; txtMain.WordWrap = false; txtMain.AcceptsReturn = true; txtMain.Font = new Font("Consolas", 10f); txtMain.TextChanged += new EventHandler(delegate(object s, EventArgs e) { lblStatus.Text = "已修改(未保存到文件)"; }); this.Controls.Add(txtMain); y += 482; lblStatus = new Label(); lblStatus.Text = "支持把文本文件拖进窗口。自动识别编码后再选另存的目标编码。"; lblStatus.Location = new Point(x, y); lblStatus.AutoSize = true; lblStatus.ForeColor = COL_GRAY; this.Controls.Add(lblStatus); } private Button MkBtn(string text, int px, int py, int w, bool primary) { Button b = new Button(); b.Text = text; b.Location = new Point(px, py); b.Size = new Size(w, 28); b.FlatStyle = FlatStyle.Flat; if (primary) { b.BackColor = COL_GREEN; b.ForeColor = Color.White; b.FlatAppearance.BorderSize = 0; } else { b.FlatAppearance.BorderColor = COL_GREEN; b.ForeColor = Color.FromArgb(0, 110, 66); } this.Controls.Add(b); return b; } private void OnDragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; } private void OnDragDrop(object sender, DragEventArgs e) { string[] f = (string[])e.Data.GetData(DataFormats.FileDrop); if (f != null && f.Length > 0 && File.Exists(f[0])) LoadFile(f[0]); } private void OpenClick(object sender, EventArgs e) { using (OpenFileDialog d = new OpenFileDialog()) { d.Title = "打开文本文件"; d.Filter = "所有文件 (*.*)|*.*"; if (d.ShowDialog() == DialogResult.OK) LoadFile(d.FileName); } } private Encoding PickEnc() { switch (cmbEnc.SelectedIndex) { case 1: return new UTF8Encoding(false); case 2: return Encoding.GetEncoding("GBK"); case 3: return Encoding.GetEncoding("Unicode"); default: return null; // 自动 } } private void LoadFile(string path) { try { loading = true; byte[] data = File.ReadAllBytes(path); Encoding enc; string text = TextOps.Decode(data, out enc); txtMain.Text = text; currentEnc = enc; currentFile = path; if (enc is UTF8Encoding) cmbEnc.SelectedIndex = 1; else if (enc.CodePage == 936) cmbEnc.SelectedIndex = 2; else if (enc.CodePage == 1200) cmbEnc.SelectedIndex = 3; else cmbEnc.SelectedIndex = 0; lblStatus.Text = Path.GetFileName(path) + "(" + enc.EncodingName + ")已打开," + data.Length + " 字节"; } catch (Exception ex) { lblStatus.Text = "打开失败:" + ex.Message; } finally { loading = false; } } private void ReloadIfFile() { if (loading) return; if (currentFile.Length > 0 && File.Exists(currentFile)) LoadFile(currentFile); } private void SaveClick(object sender, EventArgs e) { using (SaveFileDialog d = new SaveFileDialog()) { d.Title = "另存为"; d.Filter = "所有文件 (*.*)|*.*"; d.FileName = currentFile.Length > 0 ? Path.GetFileName(currentFile) : "output.txt"; if (d.ShowDialog() != DialogResult.OK) return; try { Encoding enc = PickEnc(); if (enc == null) enc = currentEnc ?? new UTF8Encoding(false); File.WriteAllText(d.FileName, txtMain.Text, enc); lblStatus.Text = "已保存:" + d.FileName + "(" + enc.EncodingName + ")"; } catch (Exception ex) { lblStatus.Text = "保存失败:" + ex.Message; } } } private void ApplyClick(object sender, EventArgs e) { string t = txtMain.Text; int op = cmbOp.SelectedIndex; string r = TextOps.Apply(t, op); if (op == TextOps.OP_NOBOM) { if (r != t) { txtMain.Text = r; lblStatus.Text = "已去掉 BOM 字符。另存时选择 UTF-8(无 BOM)可避免再生成。"; } else lblStatus.Text = "没有检测到 BOM 字符。"; return; } txtMain.Text = r; lblStatus.Text = "处理完成。"; } private void ReplaceClick(object sender, EventArgs e) { if (txtFind.Text.Length == 0) { lblStatus.Text = "请填写查找内容。"; return; } int count = TextOps.Count(txtMain.Text, txtFind.Text); txtMain.Text = txtMain.Text.Replace(txtFind.Text, txtRepl.Text); lblStatus.Text = "替换完成,共 " + count + " 处。"; } } // ── 与界面解耦的纯逻辑,--selftest 直接调这里 ───────────────────────── public static class TextOps { public const int OP_NOEMPTY = 0; public const int OP_DEDUP = 1; public const int OP_SORT_ASC = 2; public const int OP_SORT_DESC = 3; public const int OP_TRIM = 4; public const int OP_UPPER = 5; public const int OP_LOWER = 6; public const int OP_NUMBER = 7; public const int OP_TO_LF = 8; public const int OP_TO_CRLF = 9; public const int OP_NOBOM = 10; public static readonly string[] OP_NAMES = new string[] { "去空行", "去重行(保留首次出现)", "排序(升序)", "排序(降序)", "删除首尾空白", "全部转大写", "全部转小写", "加行号", "CRLF → LF", "LF → CRLF", "去掉 BOM" }; // 三种换行都当换行:\r\n、单独的 \n、单独的 \r(老 Mac 存的文件) public static string[] SplitLines(string t) { if (t == null) t = ""; return t.Replace("\r\n", "\n").Replace('\r', '\n').Split('\n'); } // 空行判定用 Trim 后长度,只有空格/制表符的行也算空行 public static string JoinCompact(string[] lines, bool dedup) { StringBuilder sb = new StringBuilder(); List seen = new List(); bool first = true; foreach (string l in lines) { if (l == null) continue; if (l.Trim().Length == 0) continue; if (dedup) { if (seen.Contains(l)) continue; seen.Add(l); } if (!first) sb.Append("\r\n"); sb.Append(l); first = false; } return sb.ToString(); } public static string Apply(string t, int op) { if (t == null) t = ""; string[] lines; StringBuilder sb; int i; switch (op) { case OP_NOEMPTY: return JoinCompact(SplitLines(t), false); case OP_DEDUP: return JoinCompact(SplitLines(t), true); case OP_SORT_ASC: lines = SplitLines(t); Array.Sort(lines, StringComparer.Ordinal); return string.Join("\r\n", lines); case OP_SORT_DESC: lines = SplitLines(t); Array.Sort(lines, StringComparer.Ordinal); Array.Reverse(lines); return string.Join("\r\n", lines); case OP_TRIM: lines = SplitLines(t); for (i = 0; i < lines.Length; i++) lines[i] = lines[i].Trim(); return string.Join("\r\n", lines); case OP_UPPER: return t.ToUpperInvariant(); case OP_LOWER: return t.ToLowerInvariant(); case OP_NUMBER: lines = SplitLines(t); sb = new StringBuilder(); for (i = 0; i < lines.Length; i++) { if (i > 0) sb.Append("\r\n"); sb.Append((i + 1).ToString()).Append(". ").Append(lines[i]); } return sb.ToString(); case OP_TO_LF: return t.Replace("\r\n", "\n").Replace('\r', '\n'); case OP_TO_CRLF: // 先统一成 LF 再一次性转 CRLF,避免出现 \r\r\n return t.Replace("\r\n", "\n").Replace('\r', '\n').Replace("\n", "\r\n"); case OP_NOBOM: return (t.Length > 0 && t[0] == '\uFEFF') ? t.Substring(1) : t; } return t; } // 编码判定顺序:UTF-8 BOM → UTF-16LE BOM → 严格 UTF-8 → GBK public static string Decode(byte[] data, out Encoding enc) { if (data == null) data = new byte[0]; if (data.Length >= 3 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF) { enc = new UTF8Encoding(true); return enc.GetString(data); } if (data.Length >= 2 && data[0] == 0xFF && data[1] == 0xFE) { enc = Encoding.Unicode; return enc.GetString(data); } try { UTF8Encoding strict = new UTF8Encoding(false, true); string s = strict.GetString(data); // 非法字节序列会抛,说明不是 UTF-8 enc = new UTF8Encoding(false); return s; } catch { enc = Encoding.GetEncoding(936); return enc.GetString(data); } } public static int Count(string src, string find) { if (src == null || find == null || find.Length == 0) return 0; int c = 0, pos = 0; while ((pos = src.IndexOf(find, pos, StringComparison.Ordinal)) >= 0) { c++; pos += find.Length; } return c; } } // 命令行自测:不弹窗,纯逻辑跑一遍,退出码 0 = 全过,1 = 有失败 public static class SelfTest { private static int _pass = 0; private static int _fail = 0; private static List _lines = new List(); private static string Esc(string s) { if (s == null) return ""; if (s.Length > 90) s = s.Substring(0, 90) + "…"; return s.Replace("\r", "\\r").Replace("\n", "\\n").Replace("\t", "\\t"); } private static void Check(string name, string got, string want) { if (got == null) got = ""; if (want == null) want = ""; if (got == want) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " 期望[" + Esc(want) + "] 实际[" + Esc(got) + "]"); } } private static void CheckInt(string name, int got, int want) { Check(name, got.ToString(), want.ToString()); } private static void CheckEnc(string name, Encoding got, int wantCodePage) { CheckInt(name, got == null ? -1 : got.CodePage, wantCodePage); } public static int Run(string dir) { if (string.IsNullOrEmpty(dir)) dir = Path.Combine(Path.GetTempPath(), "greentool-text-selftest"); try { Directory.CreateDirectory(dir); _lines.Add("文本工具 自测(" + dir + ")"); // ── 换行归一 ── Check("三种换行都当换行", string.Join("|", TextOps.SplitLines("a\r\nb\nc\rd")), "a|b|c|d"); // ── 去空行 ── Check("去空行(只有空格/制表符的行也算空行)", TextOps.Apply("a\r\n\r\n \r\nb\r\n\t\r\n", TextOps.OP_NOEMPTY), "a\r\nb"); Check("去空行不吃正文里的缩进", TextOps.Apply(" a \r\nb", TextOps.OP_NOEMPTY), " a \r\nb"); // ── 去重 ── Check("去重保留首次出现的顺序", TextOps.Apply("b\r\na\r\nb\r\nc\r\na", TextOps.OP_DEDUP), "b\r\na\r\nc"); Check("去重不碰空行(空行本来就被去掉)", TextOps.Apply("x\r\n\r\nx", TextOps.OP_DEDUP), "x"); // ── 排序 ── Check("排序升序", TextOps.Apply("b\r\na\r\nc", TextOps.OP_SORT_ASC), "a\r\nb\r\nc"); Check("排序降序", TextOps.Apply("b\r\na\r\nc", TextOps.OP_SORT_DESC), "c\r\nb\r\na"); // ── 去首尾空白 ── Check("去首尾空白", TextOps.Apply(" a \r\n\tb\t", TextOps.OP_TRIM), "a\r\nb"); // ── 大小写 ── Check("转大写(中文不受影响)", TextOps.Apply("aB1中文 ü", TextOps.OP_UPPER), "AB1中文 Ü"); Check("转小写", TextOps.Apply("AbC", TextOps.OP_LOWER), "abc"); // ── 加行号:历史上这里漏了换行,所有行被粘成一行 ── Check("加行号每行都换行", TextOps.Apply("a\r\nb\r\n\r\nc", TextOps.OP_NUMBER), "1. a\r\n2. b\r\n3. \r\n4. c"); // ── 换行风格 ── Check("CRLF→LF", TextOps.Apply("a\r\nb\r\nc", TextOps.OP_TO_LF), "a\nb\nc"); Check("LF→CRLF", TextOps.Apply("a\nb\nc", TextOps.OP_TO_CRLF), "a\r\nb\r\nc"); Check("已经是 CRLF 时不会变成 \\r\\r\\n", TextOps.Apply("a\r\nb", TextOps.OP_TO_CRLF), "a\r\nb"); // ── BOM ── Check("去掉 BOM 字符", TextOps.Apply("\uFEFF中文", TextOps.OP_NOBOM), "中文"); Check("本来没有 BOM 时原样返回", TextOps.Apply("中文", TextOps.OP_NOBOM), "中文"); // ── 幂等:跑两次结果必须一样,否则用户点两次就坏 ── string once = TextOps.Apply("x\r\n\r\nx\r\ny", TextOps.OP_DEDUP); Check("去重跑两次结果一致", TextOps.Apply(once, TextOps.OP_DEDUP), once); string lf = TextOps.Apply("a\r\nb", TextOps.OP_TO_LF); Check("CRLF→LF 跑两次结果一致", TextOps.Apply(lf, TextOps.OP_TO_LF), lf); string num = TextOps.Apply("a\r\nb", TextOps.OP_NUMBER); Check("加行号跑两次不会叠加编号", TextOps.Apply(num, TextOps.OP_NUMBER), "1. 1. a\r\n2. 2. b"); // ── 替换计数 ── CheckInt("aaa 里的 aa 算 1 处(不重叠)", TextOps.Count("aaa", "aa"), 1); CheckInt("中文替换计数", TextOps.Count("编号编号编", "编号"), 2); CheckInt("查找内容为空时记 0", TextOps.Count("abc", ""), 0); // ── 编码识别 ── Encoding gbk = Encoding.GetEncoding(936); byte[] utf8Body = new UTF8Encoding(false).GetBytes("中文测试\n第二行"); File.WriteAllBytes(Path.Combine(dir, "t-utf8.txt"), utf8Body); Encoding e1; string s1 = TextOps.Decode(utf8Body, out e1); CheckEnc("UTF-8 无 BOM 认成 UTF-8", e1, 65001); Check("UTF-8 中文解码正确", TextOps.Apply(s1, TextOps.OP_NOBOM), "中文测试\n第二行"); byte[] bomBody = new UTF8Encoding(false).GetBytes("带BOM的中文"); byte[] withBom = new byte[3 + bomBody.Length]; withBom[0] = 0xEF; withBom[1] = 0xBB; withBom[2] = 0xBF; Array.Copy(bomBody, 0, withBom, 3, bomBody.Length); File.WriteAllBytes(Path.Combine(dir, "t-utf8bom.txt"), withBom); Encoding e2; string s2 = TextOps.Decode(withBom, out e2); CheckEnc("UTF-8 带 BOM 认成 UTF-8", e2, 65001); Check("带 BOM 的文件去掉 BOM 后正文正确", TextOps.Apply(s2, TextOps.OP_NOBOM), "带BOM的中文"); byte[] gbkBody = gbk.GetBytes("GBK 编码的中文:绿色工具箱"); File.WriteAllBytes(Path.Combine(dir, "t-gbk.txt"), gbkBody); Encoding e3; string s3 = TextOps.Decode(gbkBody, out e3); CheckEnc("GBK 文件认成 GBK", e3, 936); Check("GBK 中文解码正确(不乱码)", s3, "GBK 编码的中文:绿色工具箱"); byte[] u16Body = Encoding.Unicode.GetBytes("UTF16 中文"); byte[] u16All = new byte[2 + u16Body.Length]; u16All[0] = 0xFF; u16All[1] = 0xFE; Array.Copy(u16Body, 0, u16All, 2, u16Body.Length); File.WriteAllBytes(Path.Combine(dir, "t-utf16.txt"), u16All); Encoding e4; string s4 = TextOps.Decode(u16All, out e4); CheckEnc("UTF-16LE 认成 Unicode", e4, 1200); Check("UTF-16 中文解码正确", TextOps.Apply(s4, TextOps.OP_NOBOM), "UTF16 中文"); // ── 另存为再读回:GBK 存盘(模拟「另存为 GBK」这一步)── string rt = "存成GBK再读回来:绿色工具箱"; byte[] rtBytes = gbk.GetBytes(rt); File.WriteAllBytes(Path.Combine(dir, "t-gbk-roundtrip.txt"), rtBytes); Encoding e5; string s5 = TextOps.Decode(File.ReadAllBytes(Path.Combine(dir, "t-gbk-roundtrip.txt")), out e5); Check("另存为 GBK 后读回内容一致", s5, rt); CheckEnc("读回时仍认成 GBK", e5, 936); // ── 边界输入不炸 ── Check("空文本去空行返回空", TextOps.Apply("", TextOps.OP_NOEMPTY), ""); Check("空文本加行号返回「1. 」", TextOps.Apply("", TextOps.OP_NUMBER), "1. "); Check("null 输入不抛异常", TextOps.Apply(null, TextOps.OP_TRIM), ""); // 只清掉本次自己写的几个文件,不动你目录里的其他东西 string[] made = new string[] { "t-utf8.txt", "t-utf8bom.txt", "t-gbk.txt", "t-utf16.txt", "t-gbk-roundtrip.txt" }; foreach (string f in made) { string p = Path.Combine(dir, f); if (File.Exists(p)) { try { File.Delete(p); } catch { } } } } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } _lines.Add(""); if (_fail == 0) _lines.Add("结果:共 " + (_pass + _fail) + " 项,全部通过 ✓"); else _lines.Add("结果:共 " + (_pass + _fail) + " 项,通过 " + _pass + ",失败 " + _fail + " ✗"); string all = string.Join("\r\n", _lines.ToArray()); Console.WriteLine(all); try { File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "selftest-text.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(SelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new TextToolForm()); } } }