// 批量文本替换 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法(net48 自带 csc 可编译) // 功能:整个文件夹(可含子文件夹)里的文本文件批量查找替换 // - 支持纯文本与正则两种匹配,大小写可开关 // - 编码自动识别(UTF-8/GBK/UTF-16,带 BOM 也能认),替换后按原编码原样写回 // - 二进制文件(exe/图片/压缩包)自动跳过绝不误伤 // - 默认只预览不写盘,确认无误再点执行;可选生成 .bak 备份 using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; namespace GreenToolbox { public class RepOps { public class Options { public string Find = ""; public string Replace = ""; public string[] ExtFilters = new string[0]; // 如 ".txt" ".md",小写带点 public bool Recursive = true; public bool CaseSensitive = false; public bool UseRegex = false; public bool Backup = true; } public class FileScan { public string Path; public int Matches; public string EncName; public bool Changed; // 执行替换后是否真的写了 public string Note = ""; // 跳过原因等 } public class ScanResult { public List Files = new List(); public int TotalMatches; public int SkippedBinary; public string Error = ""; } /* ---------- 编码识别(与编码批量转换同思路) ---------- */ public class EncInfo { public string Name; public int BomLen; public Encoding Enc; } public static Encoding Gbk() { return Encoding.GetEncoding(936); } 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 EncInfo Detect(byte[] d) { if (d == null || d.Length == 0) return null; if (d.Length >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF) return new EncInfo { Name = "UTF-8", BomLen = 3, Enc = new UTF8Encoding(true) }; if (d.Length >= 2 && d[0] == 0xFF && d[1] == 0xFE) return new EncInfo { Name = "UTF-16 LE", BomLen = 2, Enc = Encoding.Unicode }; if (d.Length >= 2 && d[0] == 0xFE && d[1] == 0xFF) return new EncInfo { Name = "UTF-16 BE", BomLen = 2, Enc = new UnicodeEncoding(true, true) }; // 文本文件不会有 0 字节:先拦二进制 for (int i = 0; i < d.Length; i++) if (d[i] == 0) return null; try { new UTF8Encoding(false, true).GetBytes( new UTF8Encoding(false, true).GetString(d)); return new EncInfo { Name = "UTF-8", BomLen = 0, Enc = new UTF8Encoding(false) }; } catch (DecoderFallbackException) { } if (IsGbk(d)) return new EncInfo { Name = "GBK", BomLen = 0, Enc = Gbk() }; return null; } /* ---------- 匹配与替换 ---------- */ public static Regex BuildRegex(Options o) { RegexOptions ro = RegexOptions.Multiline; if (!o.CaseSensitive) ro |= RegexOptions.IgnoreCase; string pat = o.UseRegex ? o.Find : Regex.Escape(o.Find); return new Regex(pat, ro); } public static int CountMatches(string text, Options o, Regex re) { if (string.IsNullOrEmpty(o.Find)) return 0; return re.Matches(text).Count; } public static string DoReplace(string text, Options o, Regex re) { return re.Replace(text, delegate (Match m) { return o.Replace; }); } /* ---------- 扫描 ---------- */ static bool ExtMatch(string file, string[] filters) { if (filters == null || filters.Length == 0) return true; string ext = Path.GetExtension(file).ToLowerInvariant(); foreach (string f in filters) if (ext == f) return true; return false; } public static void CollectFiles(string folder, Options o, List out_files) { DirectoryInfo di = new DirectoryInfo(folder); foreach (FileInfo fi in di.GetFiles()) if (ExtMatch(fi.Name, o.ExtFilters)) out_files.Add(fi.FullName); if (o.Recursive) foreach (DirectoryInfo sub in di.GetDirectories()) CollectFiles(sub.FullName, o, out_files); } /* 读出文本与编码;不是可识别文本返回 null */ public static string ReadText(string path, out EncInfo enc) { enc = null; byte[] d = File.ReadAllBytes(path); enc = Detect(d); if (enc == null) return null; return enc.Enc.GetString(d, enc.BomLen, d.Length - enc.BomLen); } /* 按原编码写回,BOM 跟原来一致 */ public static void WriteText(string path, string text, EncInfo enc) { byte[] body = enc.Enc.GetBytes(text); byte[] outb = new byte[enc.BomLen + body.Length]; if (enc.BomLen > 0) Array.Copy(enc.Enc.GetPreamble(), outb, enc.BomLen); Array.Copy(body, 0, outb, enc.BomLen, body.Length); File.WriteAllBytes(path, outb); } /* 扫描(只统计,不写盘) */ public static ScanResult Scan(string folder, Options o) { ScanResult r = new ScanResult(); if (!Directory.Exists(folder)) { r.Error = "文件夹不存在"; return r; } if (string.IsNullOrEmpty(o.Find)) { r.Error = "请先填查找内容"; return r; } Regex re; try { re = BuildRegex(o); } catch (ArgumentException ex) { r.Error = "正则表达式有误: " + ex.Message; return r; } List files = new List(); try { CollectFiles(folder, o, files); } catch (Exception ex) { r.Error = "读取文件夹失败: " + ex.Message; return r; } files.Sort(StringComparer.OrdinalIgnoreCase); foreach (string f in files) { FileScan fs = new FileScan(); fs.Path = f; try { EncInfo enc; string text = ReadText(f, out enc); if (text == null) { fs.EncName = "二进制"; fs.Note = "跳过(不是文本)"; r.SkippedBinary++; } else { fs.EncName = enc.Name; fs.Matches = CountMatches(text, o, re); } } catch (Exception ex) { fs.EncName = "?"; fs.Note = "读不了: " + ex.Message; } r.Files.Add(fs); r.TotalMatches += fs.Matches; } return r; } /* 执行替换:先按原编码写回,可选 .bak 备份 */ public static ScanResult Replace(string folder, Options o) { ScanResult r = Scan(folder, o); if (r.Error != "") return r; Regex re = BuildRegex(o); foreach (FileScan fs in r.Files) { if (fs.Matches <= 0 || fs.Note != "") continue; try { EncInfo enc; string text = ReadText(fs.Path, out enc); if (enc == null) continue; string after = DoReplace(text, o, re); if (after == text) { fs.Changed = false; continue; } if (o.Backup) File.WriteAllBytes(fs.Path + ".bak", File.ReadAllBytes(fs.Path)); WriteText(fs.Path, after, enc); fs.Changed = true; } catch (Exception ex) { fs.Note = "写失败: " + ex.Message; fs.Changed = false; } } return r; } } public class RepForm : Form { TextBox _dir, _find, _repl, _ext; CheckBox _sub, _case, _regex, _bak; Button _scan, _go; ListView _list; Label _stat; // 测试钩子 internal TextBox TDir { get { return _dir; } } internal TextBox TFind { get { return _find; } } internal TextBox TRepl { get { return _repl; } } internal RepOps.Options Collect() { RepOps.Options o = new RepOps.Options(); o.Find = _find.Text; o.Replace = _repl.Text; o.Recursive = _sub.Checked; o.CaseSensitive = _case.Checked; o.UseRegex = _regex.Checked; o.Backup = _bak.Checked; List exts = new List(); foreach (string p in _ext.Text.Split(new char[] { ';', ',' })) { string e = p.Trim().ToLowerInvariant(); if (e == "") continue; if (!e.StartsWith("*.")) e = "*." + e.TrimStart('.'); exts.Add(e.Substring(1)); } o.ExtFilters = exts.ToArray(); return o; } internal List DoScan() { return RunCore(false); } /* CLI/截图用:预填三栏并在窗体显示后自动扫描 */ internal void PrefillScan(string dir, string find, string repl) { _dir.Text = dir; _find.Text = find; _repl.Text = repl; Shown += delegate { try { RunCore(false); } catch { } }; } internal int DoReplace() { List r = RunCore(true); int n = 0; foreach (RepOps.FileScan fs in r) if (fs.Changed) n++; return n; } List RunCore(bool apply) { RepOps.Options o = Collect(); RepOps.ScanResult r = apply ? RepOps.Replace(_dir.Text, o) : RepOps.Scan(_dir.Text, o); _list.Items.Clear(); if (r.Error != "") { _stat.Text = r.Error; return r.Files; } foreach (RepOps.FileScan fs in r.Files) { ListViewItem it = new ListViewItem(Path.GetFileName(fs.Path)); it.SubItems.Add(fs.Matches.ToString()); it.SubItems.Add(fs.EncName); it.SubItems.Add(fs.Note); it.BackColor = fs.Note != "" ? Color.FromArgb(255, 248, 240) : Color.White; _list.Items.Add(it); } int changed = 0; foreach (RepOps.FileScan fs in r.Files) if (fs.Changed) changed++; _stat.Text = apply ? string.Format("完成:改写 {0} 个文件,共替换 {1} 处,跳过二进制 {2} 个", changed, r.TotalMatches, r.SkippedBinary) : string.Format("预览:{0} 个文件命中 {1} 处,跳过二进制 {2} 个(尚未写盘,确认后点执行替换)", CountHit(r), r.TotalMatches, r.SkippedBinary); return r.Files; } static int CountHit(RepOps.ScanResult r) { int n = 0; foreach (RepOps.FileScan fs in r.Files) if (fs.Matches > 0) n++; return n; } public RepForm() { Text = "批量文本替换 - 绿色工具箱"; Font = new Font("Microsoft YaHei UI", 9f); AllowDrop = true; Size = new Size(760, 560); StartPosition = FormStartPosition.CenterScreen; int y = 12; Label l1 = new Label { Text = "文件夹:", Left = 12, Top = y + 3, AutoSize = true }; _dir = new TextBox { Left = 68, Top = y, Width = 560, Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right }; Button bb = new Button { Text = "浏览…", Left = 640, Top = y - 1, Width = 70, Anchor = AnchorStyles.Top | AnchorStyles.Right }; bb.Click += delegate { using (FolderBrowserDialog fb = new FolderBrowserDialog()) if (fb.ShowDialog(this) == DialogResult.OK) _dir.Text = fb.SelectedPath; }; Controls.Add(l1); Controls.Add(_dir); Controls.Add(bb); y += 32; Label l2 = new Label { Text = "查找:", Left = 12, Top = y + 3, AutoSize = true }; _find = new TextBox { Left = 68, Top = y, Width = 280 }; Label l3 = new Label { Text = "替换为:", Left = 360, Top = y + 3, AutoSize = true }; _repl = new TextBox { Left = 420, Top = y, Width = 290, Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right }; Controls.Add(l2); Controls.Add(_find); Controls.Add(l3); Controls.Add(_repl); y += 32; Label l4 = new Label { Text = "扩展名:", Left = 12, Top = y + 3, AutoSize = true }; _ext = new TextBox { Left = 68, Top = y, Width = 560, Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right, Text = "*.txt;*.md;*.csv;*.html;*.htm;*.xml;*.json;*.js;*.css;*.cs;*.java;*.py;*.log;*.ini" }; Controls.Add(l4); Controls.Add(_ext); y += 32; _sub = new CheckBox { Text = "含子文件夹", Left = 68, Top = y, AutoSize = true, Checked = true }; _case = new CheckBox { Text = "大小写敏感", Left = 175, Top = y, AutoSize = true }; _regex = new CheckBox { Text = "正则表达式", Left = 285, Top = y, AutoSize = true }; _bak = new CheckBox { Text = "改前生成 .bak 备份", Left = 395, Top = y, AutoSize = true, Checked = true }; Controls.Add(_sub); Controls.Add(_case); Controls.Add(_regex); Controls.Add(_bak); y += 32; _scan = new Button { Text = "扫描预览", Left = 68, Top = y, Width = 110, Height = 30 }; _go = new Button { Text = "执行替换", Left = 190, Top = y, Width = 110, Height = 30 }; _go.Click += delegate { RunCore(true); }; _scan.Click += delegate { RunCore(false); }; Controls.Add(_scan); Controls.Add(_go); y += 40; _list = new ListView { Left = 12, Top = y, Width = 700, Height = 340, Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right, View = View.Details, FullRowSelect = true, HideSelection = true }; _list.Columns.Add("文件", 300); _list.Columns.Add("命中", 60); _list.Columns.Add("编码", 90); _list.Columns.Add("备注", 220); Controls.Add(_list); y += 346; _stat = new Label { Text = "先扫描预览,确认无误再执行替换。默认给每个改动文件留 .bak 备份。", Left = 12, Top = y, Width = 700, Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right, ForeColor = Color.FromArgb(0, 110, 60) }; Controls.Add(_stat); DragEnter += delegate (object s, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; }; DragDrop += delegate (object s, DragEventArgs e) { string[] paths = (string[])e.Data.GetData(DataFormats.FileDrop); if (paths != null && paths.Length > 0 && Directory.Exists(paths[0])) _dir.Text = paths[0]; }; AcceptButton = _scan; } } } namespace GreenToolbox { using System; internal static class RepProgram { private static int _pass, _fail; private static readonly List _lines = new List(); static void Check(string name, string got, string want) { bool ok = got == want; _lines.Add((ok ? "[ok] " : "[!!] ") + name + " => " + got + (ok ? "" : " (期望 " + want + ")")); if (ok) _pass++; else _fail++; } static void CheckTrue(string name, bool ok) { _lines.Add((ok ? "[ok] " : "[!!] ") + name); if (ok) _pass++; else _fail++; } static void Flush() { _lines.Add(string.Format("结果: {0} 通过, {1} 失败", _pass, _fail)); string p = Path.Combine(Path.GetTempPath(), "selftest-filereplace.txt"); File.WriteAllLines(p, _lines.ToArray(), new UTF8Encoding(true)); } static string WriteFile(string dir, string name, string text, Encoding enc) { string p = Path.Combine(dir, name); File.WriteAllText(p, text, enc); return p; } static byte[] Raw(string p) { return File.ReadAllBytes(p); } private static void RunSelfTest() { string root = Path.Combine(Path.GetTempPath(), "fr-test-" + DateTime.Now.Ticks.ToString("x")); string sub = Path.Combine(root, "sub"); Directory.CreateDirectory(sub); try { // 准备测试树 string a = WriteFile(root, "a.txt", "苹果苹果香蕉\r\n苹果 again\r\nEND", new UTF8Encoding(true)); // BOM string b = WriteFile(root, "b.txt", "红色蓝色红色绿色", RepOps.Gbk()); // GBK string c = WriteFile(root, "c.md", "# title abc Abc ABC", new UTF8Encoding(false)); // 无 BOM string d = WriteFile(sub, "d.txt", "year 2026, month 03", new UTF8Encoding(false)); string bin = WriteFile(root, "bin.dat", "te\x0bst", Encoding.ASCII); // 含 0 字节 using (FileStream fs = new FileStream(bin, FileMode.Append)) fs.Write(new byte[] { 0x00, 0x01 }, 0, 2); string nomatch = WriteFile(root, "e.log", "nothing here", new UTF8Encoding(false)); RepOps.Options o1 = new RepOps.Options(); o1.Find = "苹果"; o1.Replace = "橙子"; // 1. 扫描:递归 5 个文本文件(bin 跳过) RepOps.ScanResult r = RepOps.Scan(root, o1); CheckTrue("递归扫描不报错", r.Error == ""); Check("扫描文件总数(含跳过)", r.Files.Count.ToString(), "6"); Check("二进制跳过数", r.SkippedBinary.ToString(), "1"); Check("总命中", r.TotalMatches.ToString(), "3"); // 2. 各文件命中数与编码识别 RepOps.FileScan fa = r.Files.Find(delegate (RepOps.FileScan x) { return x.Path == a; }); RepOps.FileScan fb = r.Files.Find(delegate (RepOps.FileScan x) { return x.Path == b; }); Check("a.txt 命中", fa.Matches.ToString(), "3"); Check("a.txt 编码", fa.EncName, "UTF-8"); Check("b.txt 命中(无苹果)", fb.Matches.ToString(), "0"); Check("b.txt 编码", fb.EncName, "GBK"); // 3. 不递归:不含子文件 RepOps.Options onr = new RepOps.Options(); onr.Find = "苹果"; onr.Recursive = false; RepOps.ScanResult rn = RepOps.Scan(root, onr); CheckTrue("非递归不含子目录", rn.Files.Find( delegate (RepOps.FileScan x) { return x.Path == d; }) == null); // 4. 扩展名过滤 RepOps.Options oe = new RepOps.Options(); oe.Find = "苹果"; oe.ExtFilters = new string[] { ".md" }; RepOps.ScanResult re2 = RepOps.Scan(root, oe); Check("扩展名过滤只留 md", re2.Files.Count.ToString(), "1"); // 5. 大小写开关 RepOps.Options oc1 = new RepOps.Options(); oc1.Find = "abc"; oc1.CaseSensitive = false; RepOps.ScanResult rc1 = RepOps.Scan(root, oc1); RepOps.FileScan fc1 = rc1.Files.Find(delegate (RepOps.FileScan x) { return x.Path == c; }); Check("忽略大小写命中", fc1.Matches.ToString(), "3"); RepOps.Options oc2 = new RepOps.Options(); oc2.Find = "abc"; oc2.CaseSensitive = true; RepOps.ScanResult rc2 = RepOps.Scan(root, oc2); RepOps.FileScan fc2 = rc2.Files.Find(delegate (RepOps.FileScan x) { return x.Path == c; }); Check("大小写敏感命中", fc2.Matches.ToString(), "1"); // 6. 正则 RepOps.Options orx = new RepOps.Options(); orx.Find = "\\d{4}"; orx.UseRegex = true; RepOps.ScanResult rx = RepOps.Scan(root, orx); RepOps.FileScan fx = rx.Files.Find(delegate (RepOps.FileScan x) { return x.Path == d; }); Check("正则命中", fx.Matches.ToString(), "1"); // 7. 替换 + 编码保持 + 备份 RepOps.Options og = new RepOps.Options(); og.Find = "红色"; og.Replace = "黑色"; og.Backup = true; RepOps.Replace(root, og); string bAfter = RepOps.Gbk().GetString(Raw(b), 0, Raw(b).Length); CheckTrue("GBK 替换后内容正确", bAfter == "黑色蓝色黑色绿色"); CheckTrue("GBK 无 BOM 保持", Raw(b)[0] != 0xEF && Raw(b)[0] != 0xFF); CheckTrue("备份已生成", File.Exists(b + ".bak")); CheckTrue("备份是原内容", RepOps.Gbk().GetString(Raw(b + ".bak"), 0, Raw(b + ".bak").Length) == "红色蓝色红色绿色"); // 8. UTF-8 BOM 保持 RepOps.Options ou = new RepOps.Options(); ou.Find = "苹果"; ou.Replace = "橙子"; ou.Backup = false; RepOps.Replace(root, ou); byte[] ra = Raw(a); CheckTrue("BOM 保持", ra[0] == 0xEF && ra[1] == 0xBB && ra[2] == 0xBF); string aText = new UTF8Encoding(true).GetString(ra, 3, ra.Length - 3); CheckTrue("UTF-8 替换后正确", aText == "橙子橙子香蕉\r\n橙子 again\r\nEND"); // 9. 无 BOM UTF-8 不被加 BOM byte[] rc = Raw(c); CheckTrue("无 BOM 仍无 BOM", rc[0] != 0xEF); // 10. 换行保持 CheckTrue("CRLF 保持", aText.Contains("\r\n")); // 11. 二进制未被动过(7 字节 = te\x0bst 5 字节 + 0x00 0x01) byte[] rb = File.ReadAllBytes(bin); CheckTrue("二进制未改写", rb.Length == 7 && rb[5] == 0x00 && rb[6] == 0x01); // 12. 再扫一遍:命中归零 RepOps.ScanResult rz = RepOps.Scan(root, ou); Check("替换后命中归零", rz.TotalMatches.ToString(), "0"); // 13. 空查找 RepOps.Options oz = new RepOps.Options(); oz.Find = ""; CheckTrue("空查找不炸", RepOps.Scan(root, oz).Error != ""); // 14. 目录不存在 RepOps.Options od = new RepOps.Options(); od.Find = "x"; CheckTrue("目录不存在报错", RepOps.Scan(Path.Combine(root, "no-such"), od).Error != ""); // 15. 正则非法报错 RepOps.Options obad = new RepOps.Options(); obad.Find = "([unclosed"; obad.UseRegex = true; CheckTrue("非法正则报错", RepOps.Scan(root, obad).Error != ""); // 16. 大小写不敏感替换(用正则转义路径) RepOps.Options oi = new RepOps.Options(); oi.Find = "ABC"; oi.Replace = "XYZ"; oi.Backup = false; RepOps.ScanResult ri = RepOps.Scan(root, oi); RepOps.FileScan fi = ri.Files.Find(delegate (RepOps.FileScan x) { return x.Path == c; }); RepOps.Replace(root, oi); string cAfter = new UTF8Encoding(false).GetString(Raw(c)); CheckTrue("忽略大小写替换生效", cAfter.Contains("XYZ XYZ XYZ")); // 17. Form 层:构造、改字段、扫描不炸 RepForm form = new RepForm(); try { form.TDir.Text = root; form.TFind.Text = "nothing"; List lf = form.DoScan(); CheckTrue("Form 扫描不炸", lf.Count > 0); } finally { form.Dispose(); } } finally { try { Directory.Delete(root, true); } catch { } } } [STAThread] private static int Main(string[] args) { if (args.Length > 0 && args[0] == "--selftest") { try { RunSelfTest(); } catch (Exception ex) { _lines.Add("[!!] 自测异常: " + ex.Message); _fail++; } Flush(); return _fail == 0 ? 0 : 1; } try { Application.ThreadException += delegate (object s, System.Threading.ThreadExceptionEventArgs e) { File.WriteAllText(Path.Combine(Path.GetTempPath(), "filereplace-crash.txt"), "ThreadException:\r\n" + e.Exception, new UTF8Encoding(true)); }; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); RepForm form = new RepForm(); if (args.Length >= 2) form.PrefillScan(args[0], args[1], args.Length > 2 ? args[2] : ""); Application.Run(form); } catch (Exception ex) { File.WriteAllText(Path.Combine(Path.GetTempPath(), "filereplace-crash.txt"), ex.ToString(), new UTF8Encoding(true)); throw; } return 0; } } }