// 批量重命名 - 绿色工具箱 // C# 5.0 语法,零依赖。规则:查找替换 / 前后缀 / 序号 / 扩展名 / 加日期 // 安全设计:先预览再执行;执行前检测重名冲突;不动内容只改名字 using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public class RenameToolForm : Form { private static readonly Color COL_GREEN = Color.FromArgb(0, 145, 88); private static readonly Color COL_BG = Color.White; private static readonly Color COL_PANEL = Color.FromArgb(245, 249, 246); private static readonly Color COL_GRAY = Color.FromArgb(120, 130, 124); private TextBox txtFolder; private ListView lv; private ComboBox cmbRule; private Panel pnlRule; private TextBox txtFind, txtReplace, txtPrefix, txtSuffix, txtBase, txtStart, txtStep, txtPad, txtExt; private CheckBox chkCase, chkKeepExt, chkRegex, chkUseDate; private ComboBox cmbCase; private Button btnScan, btnDo, btnUndo; private Label lblStatus; private const int RULE_REPLACE = 0; private const int RULE_FIX = 1; private const int RULE_NUM = 2; private const int RULE_EXT = 3; private const int RULE_DATE = 4; private const int RULE_CASE = 5; public RenameToolForm() { InitUi(); } private void InitUi() { this.Text = "批量重命名 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 9.5f); this.BackColor = COL_BG; this.ForeColor = Color.FromArgb(34, 40, 36); this.ClientSize = new Size(860, 620); this.MinimumSize = new Size(780, 560); this.AllowDrop = true; this.DragEnter += new DragEventHandler(OnDragEnter); this.DragDrop += new DragEventHandler(OnDragDrop); int x = 16, y = 14; Label l0 = new Label(); l0.Text = "选文件夹(也可直接把文件夹拖进窗口)→ 选规则 → 预览 → 执行"; l0.AutoSize = true; l0.ForeColor = COL_GRAY; l0.Location = new Point(x, y); this.Controls.Add(l0); y += 26; txtFolder = new TextBox(); txtFolder.Location = new Point(x, y); txtFolder.Size = new Size(700, 26); txtFolder.ReadOnly = true; txtFolder.BackColor = COL_PANEL; txtFolder.TextChanged += new EventHandler(OnFolderChanged); this.Controls.Add(txtFolder); Button btnBrowse = new Button(); btnBrowse.Text = "浏览"; btnBrowse.Location = new Point(724, y - 1); btnBrowse.Size = new Size(118, 28); btnBrowse.FlatStyle = FlatStyle.Flat; btnBrowse.FlatAppearance.BorderColor = COL_GREEN; btnBrowse.ForeColor = Color.FromArgb(0, 110, 66); btnBrowse.Click += new EventHandler(BrowseClick); this.Controls.Add(btnBrowse); y += 40; Label lr = new Label(); lr.Text = "规则:"; lr.AutoSize = true; lr.Location = new Point(x, y + 3); this.Controls.Add(lr); cmbRule = new ComboBox(); cmbRule.DropDownStyle = ComboBoxStyle.DropDownList; cmbRule.Items.Add("① 查找替换"); cmbRule.Items.Add("② 加前缀 / 后缀"); cmbRule.Items.Add("③ 序号重命名(名称+编号)"); cmbRule.Items.Add("④ 扩展名改大小写 / 替换"); cmbRule.Items.Add("⑤ 文件名加日期"); cmbRule.Items.Add("⑥ 大小写转换"); cmbRule.SelectedIndex = 0; cmbRule.Location = new Point(x + 48, y); cmbRule.Size = new Size(260, 26); cmbRule.SelectedIndexChanged += new EventHandler(RuleChanged); this.Controls.Add(cmbRule); y += 38; pnlRule = new Panel(); pnlRule.Location = new Point(x, y); pnlRule.Size = new Size(826, 64); pnlRule.BackColor = COL_PANEL; this.Controls.Add(pnlRule); BuildRulePanels(); y += 74; lv = new ListView(); lv.Location = new Point(x, y); lv.Size = new Size(826, 380); lv.View = View.Details; lv.FullRowSelect = true; lv.CheckBoxes = true; lv.HeaderStyle = ColumnHeaderStyle.Nonclickable; lv.Columns.Add(" ", 34); lv.Columns.Add("原文件名", 350); lv.Columns.Add("→", 20); lv.Columns.Add("新文件名", 350); lv.Columns.Add("状态", 70); lv.SelectedIndexChanged += new EventHandler(OnListChanged); this.Controls.Add(lv); y += 392; btnScan = new Button(); btnScan.Text = "重新扫描"; btnScan.Location = new Point(x, y); btnScan.Size = new Size(110, 32); btnScan.FlatStyle = FlatStyle.Flat; btnScan.FlatAppearance.BorderColor = COL_GREEN; btnScan.ForeColor = Color.FromArgb(0, 110, 66); btnScan.Click += new EventHandler(ScanClick); this.Controls.Add(btnScan); btnUndo = new Button(); btnUndo.Text = "撤销上次"; btnUndo.Location = new Point(604, y); btnUndo.Size = new Size(112, 32); btnUndo.FlatStyle = FlatStyle.Flat; btnUndo.FlatAppearance.BorderColor = COL_GREEN; btnUndo.ForeColor = Color.FromArgb(0, 110, 66); btnUndo.Enabled = false; btnUndo.Click += new EventHandler(UndoClick); this.Controls.Add(btnUndo); btnDo = new Button(); btnDo.Text = "执行重命名"; btnDo.Location = new Point(726, y); btnDo.Size = new Size(116, 32); btnDo.BackColor = COL_GREEN; btnDo.ForeColor = Color.White; btnDo.FlatStyle = FlatStyle.Flat; btnDo.FlatAppearance.BorderSize = 0; btnDo.Enabled = false; btnDo.Click += new EventHandler(DoRename); this.Controls.Add(btnDo); lblStatus = new Label(); lblStatus.Text = "打勾选文件(默认全选),执行前检测冲突。"; lblStatus.Location = new Point(x + 124, y + 8); lblStatus.AutoSize = true; lblStatus.ForeColor = COL_GRAY; this.Controls.Add(lblStatus); } private TextBox AddBox(string text, int px, int py, int w) { TextBox t = new TextBox(); t.Text = text; t.Location = new Point(px, py); t.Size = new Size(w, 26); t.TextChanged += new EventHandler(OnListChanged); pnlRule.Controls.Add(t); return t; } private Label AddLbl(string text, int px, int py) { Label l = new Label(); l.Text = text; l.AutoSize = true; l.Location = new Point(px, py + 4); pnlRule.Controls.Add(l); return l; } private void BuildRulePanels() { // 规则① 查找替换 AddLbl("查找", 12, 8); txtFind = AddBox("", 48, 8, 200); AddLbl("替换为", 262, 8); txtReplace = AddBox("", 316, 8, 200); chkCase = new CheckBox(); chkCase.Text = "区分大小写"; chkCase.Location = new Point(12, 38); chkCase.AutoSize = true; chkCase.CheckedChanged += new EventHandler(OnListChanged); pnlRule.Controls.Add(chkCase); chkKeepExt = new CheckBox(); chkKeepExt.Text = "不动扩展名"; chkKeepExt.Checked = true; chkKeepExt.Location = new Point(120, 38); chkKeepExt.AutoSize = true; chkKeepExt.CheckedChanged += new EventHandler(OnListChanged); pnlRule.Controls.Add(chkKeepExt); chkRegex = new CheckBox(); chkRegex.Text = "正则表达式"; chkRegex.Location = new Point(230, 38); chkRegex.AutoSize = true; chkRegex.CheckedChanged += new EventHandler(OnListChanged); pnlRule.Controls.Add(chkRegex); // 规则② 前后缀 AddLbl("前缀", 12, 38); txtPrefix = AddBox("", 48, 38, 160); AddLbl("后缀(加在扩展名前)", 230, 38); txtSuffix = AddBox("", 356, 38, 160); // 规则③ 序号 AddLbl("名称", 12, 8); txtBase = AddBox("文件", 48, 8, 120); AddLbl("起始", 186, 8); txtStart = AddBox("1", 222, 8, 50); AddLbl("步长", 286, 8); txtStep = AddBox("1", 322, 8, 50); AddLbl("位数", 386, 8); txtPad = AddBox("3", 424, 8, 40); AddLbl("例:文件001.jpg(编号 = 起始 + 步长×序,扩展名保留)", 12, 38); // 规则④ 扩展名 AddLbl("新扩展名(含点,如 .png;留空=改小写)", 12, 8); txtExt = AddBox("", 270, 8, 140); // 规则⑤ 日期 chkUseDate = new CheckBox(); chkUseDate.Text = "使用照片拍摄日期(EXIF,取不到就用修改日期)"; chkUseDate.Location = new Point(12, 8); chkUseDate.AutoSize = true; pnlRule.Controls.Add(chkUseDate); AddLbl("格式:名称_20260117.jpg,插在扩展名前", 12, 38); // 规则⑥ 大小写 cmbCase = new ComboBox(); cmbCase.DropDownStyle = ComboBoxStyle.DropDownList; cmbCase.Items.Add("全部大写"); cmbCase.Items.Add("全部小写"); cmbCase.Items.Add("首字母大写"); cmbCase.SelectedIndex = 1; cmbCase.Location = new Point(48, 8); cmbCase.Size = new Size(160, 26); cmbCase.SelectedIndexChanged += new EventHandler(OnListChanged); pnlRule.Controls.Add(cmbCase); AddLbl("方式", 12, 8); AddLbl("例:IMG_0001.JPG / 照片.jpg / my photo.jpg(扩展名保持原样)", 12, 38); for (int i = 0; i < pnlRule.Controls.Count; i++) pnlRule.Controls[i].Visible = false; ShowRule(RULE_REPLACE); } private void ShowRule(int r) { foreach (Control c in pnlRule.Controls) c.Visible = false; switch (r) { case RULE_REPLACE: SetVisible(pnlRule, new Control[] { txtFind, txtReplace, chkCase, chkKeepExt, chkRegex }); foreach (Control c in pnlRule.Controls) if (c is Label && (c.Text == "查找" || c.Text == "替换为")) c.Visible = true; break; case RULE_FIX: SetVisible(pnlRule, new Control[] { txtPrefix, txtSuffix }); foreach (Control c in pnlRule.Controls) if (c is Label && (c.Text == "前缀" || c.Text.StartsWith("后缀"))) c.Visible = true; break; case RULE_NUM: SetVisible(pnlRule, new Control[] { txtBase, txtStart, txtStep, txtPad }); foreach (Control c in pnlRule.Controls) if (c is Label && (c.Text == "名称" || c.Text == "起始" || c.Text == "步长" || c.Text == "位数" || c.Text.StartsWith("例:"))) c.Visible = true; break; case RULE_EXT: SetVisible(pnlRule, new Control[] { txtExt }); foreach (Control c in pnlRule.Controls) if (c is Label && c.Text.StartsWith("新扩展名")) c.Visible = true; break; case RULE_DATE: chkUseDate.Visible = true; foreach (Control c in pnlRule.Controls) if (c is Label && c.Text.StartsWith("格式:")) c.Visible = true; break; case RULE_CASE: SetVisible(pnlRule, new Control[] { cmbCase }); foreach (Control c in pnlRule.Controls) if (c is Label && (c.Text == "方式" || c.Text.StartsWith("例:"))) c.Visible = true; break; } } private void SetVisible(Panel p, Control[] list) { foreach (Control c in list) c.Visible = true; } public void SetFolder(string path) { txtFolder.Text = path; } public void PrefillReplace(string find, string replace) { txtFind.Text = find; txtReplace.Text = replace; } private void RuleChanged(object sender, EventArgs e) { ShowRule(cmbRule.SelectedIndex); RefreshPreview(); } 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[] items = (string[])e.Data.GetData(DataFormats.FileDrop); if (items != null && items.Length > 0 && Directory.Exists(items[0])) txtFolder.Text = items[0]; } private void BrowseClick(object sender, EventArgs e) { using (FolderBrowserDialog d = new FolderBrowserDialog()) { d.Description = "选择要批量重命名的文件夹"; if (d.ShowDialog() == DialogResult.OK) txtFolder.Text = d.SelectedPath; } } private void OnFolderChanged(object sender, EventArgs e) { Scan(); } private void ScanClick(object sender, EventArgs e) { Scan(); } private void Scan() { lv.Items.Clear(); btnDo.Enabled = false; if (txtFolder.Text.Length == 0 || !Directory.Exists(txtFolder.Text)) return; try { DirectoryInfo di = new DirectoryInfo(txtFolder.Text); FileInfo[] files = di.GetFiles(); foreach (FileInfo f in files) { ListViewItem it = new ListViewItem(""); it.Checked = true; it.SubItems.Add(f.Name); it.SubItems.Add("→"); it.SubItems.Add(""); it.SubItems.Add(""); it.Tag = f; lv.Items.Add(it); } lblStatus.Text = "共 " + files.Length + " 个文件。"; RefreshPreview(); } catch (Exception ex) { lblStatus.Text = "读取失败:" + ex.Message; } UpdateUndoButton(); } private void OnListChanged(object sender, EventArgs e) { RefreshPreview(); } private string NewName(string oldName, FileInfo fi) { int r = cmbRule.SelectedIndex; if (r == RULE_REPLACE) { if (chkRegex.Checked) return RenameOps.ApplyRegex(oldName, txtFind.Text, txtReplace.Text, chkKeepExt.Checked); return RenameOps.ApplyReplace(oldName, txtFind.Text, txtReplace.Text, chkCase.Checked, chkKeepExt.Checked); } else if (r == RULE_FIX) { return RenameOps.ApplyFix(oldName, txtPrefix.Text, txtSuffix.Text); } else if (r == RULE_EXT) { return RenameOps.ApplyExt(oldName, txtExt.Text); } else if (r == RULE_CASE) { return RenameOps.ApplyCase(oldName, cmbCase.SelectedIndex); } else if (r == RULE_DATE) { DateTime dt = DateTime.MinValue; if (chkUseDate.Checked) { try { // 尝试读 EXIF 拍摄日期(System.Drawing 属性) foreach (System.Drawing.Imaging.PropertyItem p in GetImageProps(fi)) { if (p.Id == 0x0132 || p.Id == 0x9004) // DateTime / DateTimeOriginal { string s = Encoding.ASCII.GetString(p.Value).Trim('\0'); DateTime tryDt; if (DateTime.TryParseExact(s, "yyyy:MM:dd HH:mm:ss", null, System.Globalization.DateTimeStyles.None, out tryDt)) { dt = tryDt; break; } } } } catch { } } if (dt == DateTime.MinValue) dt = fi.LastWriteTime; return RenameOps.ApplyDate(oldName, dt); } return oldName; // 编号规则由预览循环按行号单独算 } private System.Drawing.Imaging.PropertyItem[] GetImageProps(FileInfo fi) { string[] imgExt = new string[] { ".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff" }; string e = fi.Extension.ToLower(); foreach (string ie in imgExt) if (e == ie) using (System.Drawing.Image img = System.Drawing.Image.FromFile(fi.FullName)) return img.PropertyItems; return new System.Drawing.Imaging.PropertyItem[0]; } private string ReplaceCase(string src, string find, string repl) { return RenameOps.ReplaceExact(src, find, repl); } private string ReplaceIgnoreCase(string src, string find, string repl) { return RenameOps.ReplaceIgnoreCase(src, find, repl); } private void RefreshPreview() { if (lv.Items.Count == 0) return; int r = cmbRule.SelectedIndex; int counter = 0; int start = 1, pad = 3, step = 1; if (r == RULE_NUM) { int.TryParse(txtStart.Text, out start); int.TryParse(txtPad.Text, out pad); if (!int.TryParse(txtStep.Text, out step) || step < 1) step = 1; if (pad < 1) pad = 1; if (pad > 9) pad = 9; } foreach (ListViewItem it in lv.Items) { FileInfo fi = (FileInfo)it.Tag; string newName; if (r == RULE_NUM) { newName = RenameOps.ApplyNumber(fi.Name, txtBase.Text, start + counter * step, pad); counter++; } else { newName = NewName(fi.Name, fi); } it.SubItems[3].Text = newName == null ? "" : newName; string st; if (newName == null) st = "正则错!"; else { bool exists = File.Exists(Path.Combine(txtFolder.Text, newName)); st = RenameOps.PreviewState(fi.Name, newName, exists); } it.SubItems[4].Text = st; it.ForeColor = (st == "冲突!" || st == "正则错!") ? Color.FromArgb(200, 50, 50) : (st == "就绪" ? Color.FromArgb(0, 110, 66) : COL_GRAY); } btnDo.Enabled = HasWork(); } private bool HasWork() { foreach (ListViewItem it in lv.Items) if (it.Checked && it.SubItems[4].Text == "就绪") return true; return false; } private void DoRename(object sender, EventArgs e) { RefreshPreview(); List plan = new List(); foreach (ListViewItem it in lv.Items) { if (!it.Checked) continue; if (it.SubItems[4].Text != "就绪") continue; plan.Add(new string[] { ((FileInfo)it.Tag).FullName, it.SubItems[3].Text }); } if (plan.Count == 0) { MessageBox.Show("没有可执行的项目。", "批量重命名", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } DialogResult dr = MessageBox.Show( "将重命名 " + plan.Count + " 个文件,确定执行?\n(只改名字,不动文件内容)", "批量重命名", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dr != DialogResult.Yes) return; int ok = 0, err = 0; object[] r2 = RenameOps.Execute(plan); ok = (int)r2[0]; err = (int)r2[1]; List done = (List)r2[3]; if (done.Count > 0) RenameOps.SaveUndoLog(txtFolder.Text, done); UpdateUndoButton(); lblStatus.Text = "完成:成功 " + ok + " 个,失败 " + err + " 个。"; string log = (string)r2[2]; if (log.Length > 0) { MessageBox.Show(log, "部分文件没能改名", MessageBoxButtons.OK, MessageBoxIcon.Warning); } Scan(); UpdateUndoButton(); } private void UpdateUndoButton() { btnUndo.Enabled = txtFolder.Text.Length > 0 && Directory.Exists(txtFolder.Text) && RenameOps.LoadUndoLog(txtFolder.Text) != null; } private void UndoClick(object sender, EventArgs e) { if (txtFolder.Text.Length == 0 || !Directory.Exists(txtFolder.Text)) return; List log = RenameOps.LoadUndoLog(txtFolder.Text); if (log == null) { MessageBox.Show("这个文件夹没有可撤销的改名记录。", "批量重命名", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } // 反向:现在名 → 原名;跳过已被占用的原名 List plan = new List(); int skip = 0; foreach (string[] p in log) { if (!File.Exists(p[0])) { skip++; continue; } // 文件后来又被动过 if (File.Exists(p[1])) { skip++; continue; } // 原名位置已被别的文件占 plan.Add(new string[] { p[0], Path.GetFileName(p[1]) }); } if (plan.Count == 0) { MessageBox.Show("没有能安全撤销的项目(原名位置已被占用或文件不在了)。", "批量重命名", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } string tip = plan.Count == log.Count ? "把上次改名的 " + plan.Count + " 个文件改回原名,确定?" : "上次改了 " + log.Count + " 个,其中 " + plan.Count + " 个能安全撤销(其余 " + skip + " 个跳过,避免覆盖)。确定?"; if (MessageBox.Show(tip, "撤销上次", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return; object[] r2 = RenameOps.Execute(plan); // 撤销完成后清空日志(再点一次会提示没有记录) try { if (Directory.Exists(txtFolder.Text)) File.WriteAllText(RenameOps.UndoPath(txtFolder.Text), "[]", new UTF8Encoding(false)); } catch { } lblStatus.Text = "撤销完成:成功 " + (int)r2[0] + " 个,失败 " + (int)r2[1] + " 个。"; if (((string)r2[2]).Length > 0) MessageBox.Show((string)r2[2], "部分文件没能撤销", MessageBoxButtons.OK, MessageBoxIcon.Warning); Scan(); UpdateUndoButton(); } } // ── 与界面解耦的纯逻辑,--selftest 直接调这里 ───────────────────────── public static class RenameOps { public static string ReplaceExact(string src, string find, string repl) { if (src == null) return null; if (find == null || find.Length == 0) return src; return src.Replace(find, repl == null ? "" : repl); } public static string ReplaceIgnoreCase(string src, string find, string repl) { if (src == null) return null; if (find == null || find.Length == 0) return src; if (repl == null) repl = ""; string lower = src.ToLowerInvariant(); // 少数语言里 ToLower 会改变长度(如土耳其语 İ),那样下标就对不上了,退回大小写敏感 if (lower.Length != src.Length) return ReplaceExact(src, find, repl); string fLower = find.ToLowerInvariant(); StringBuilder sb = new StringBuilder(); int pos = 0; while (true) { int idx = lower.IndexOf(fLower, pos, StringComparison.Ordinal); if (idx < 0) { sb.Append(src.Substring(pos)); break; } sb.Append(src.Substring(pos, idx - pos)); sb.Append(repl); pos = idx + find.Length; } return sb.ToString(); } // 「保留扩展名」勾上 → 只替换主文件名;不勾 → 连扩展名一起当文本替换 public static string ApplyReplace(string oldName, string find, string repl, bool caseSensitive, bool keepExt) { if (oldName == null) return null; if (find == null || find.Length == 0) return oldName; string body = keepExt ? Path.GetFileNameWithoutExtension(oldName) : oldName; string tail = keepExt ? Path.GetExtension(oldName) : ""; string r = caseSensitive ? ReplaceExact(body, find, repl) : ReplaceIgnoreCase(body, find, repl); return r + tail; } public static string ApplyFix(string oldName, string prefix, string suffix) { string name = Path.GetFileNameWithoutExtension(oldName); string ext = Path.GetExtension(oldName); return (prefix == null ? "" : prefix) + name + (suffix == null ? "" : suffix) + ext; } public static int ClampPad(int pad) { if (pad < 1) return 1; if (pad > 9) return 9; return pad; } public static string ApplyNumber(string oldName, string baseName, int n, int pad) { pad = ClampPad(pad); return (baseName == null ? "" : baseName) + n.ToString(new string('0', pad)) + Path.GetExtension(oldName); } public static string ApplyExt(string oldName, string newExt) { string name = Path.GetFileNameWithoutExtension(oldName); string ext = Path.GetExtension(oldName); string ne = (newExt == null ? "" : newExt.Trim()); if (ne.Length == 0) return name + ext.ToLowerInvariant(); if (!ne.StartsWith(".")) ne = "." + ne; return name + ne; } public static string ApplyDate(string oldName, DateTime dt) { string name = Path.GetFileNameWithoutExtension(oldName); string ext = Path.GetExtension(oldName); return name + "_" + dt.ToString("yyyyMMdd") + ext; } // 正则替换。pattern 非法时返回 null(界面据此显示「正则错误」)。 public static string ApplyRegex(string oldName, string pattern, string repl, bool keepExt) { if (oldName == null) return null; if (pattern == null || pattern.Length == 0) return oldName; if (repl == null) repl = ""; System.Text.RegularExpressions.Regex rx; try { rx = new System.Text.RegularExpressions.Regex(pattern); } catch { return null; } string body = keepExt ? Path.GetFileNameWithoutExtension(oldName) : oldName; string tail = keepExt ? Path.GetExtension(oldName) : ""; return rx.Replace(body, repl) + tail; } // 大小写转换:mode 0=全大写 1=全小写 2=首字母大写(只动主名,扩展名保持原样) public static string ApplyCase(string oldName, int mode) { if (oldName == null) return null; string name = Path.GetFileNameWithoutExtension(oldName); string ext = Path.GetExtension(oldName); if (mode == 0) return name.ToUpperInvariant() + ext; if (mode == 1) return name.ToLowerInvariant() + ext; // 首字母大写:只把每个词段的首个字母转大写,其余不动 char[] cs = name.ToCharArray(); bool newWord = true; for (int i = 0; i < cs.Length; i++) { if (char.IsLetter(cs[i])) { if (newWord) cs[i] = char.ToUpperInvariant(cs[i]); newWord = false; } else if (!char.IsDigit(cs[i])) newWord = true; } return new string(cs) + ext; } public static string PreviewState(string oldName, string newName, bool exists) { if (newName == null || newName.Length == 0) return ""; if (newName == oldName) return "无变化"; if (exists) return "冲突!"; return "就绪"; } // 两阶段改名:先把每个文件挪成临时名,再落到目标名。 // 少了这一步,a→b、b→a 这种互换必然互相顶掉(File.Move 目标已存在就抛异常)。 // 落位失败会把临时名挪回原名,不留一堆 ~gt_ 开头的半成品。 public static object[] Execute(List plan) { int ok = 0, err = 0; StringBuilder log = new StringBuilder(); List staged = new List(); List done = new List(); // 成功对:[0]=现在的完整路径 [1]=改名前的完整路径 string stamp = DateTime.Now.Ticks.ToString(); for (int i = 0; i < plan.Count; i++) { string src = plan[i][0]; string dir = Path.GetDirectoryName(src); string tmp = Path.Combine(dir, "~gt_" + stamp + "_" + i + Path.GetExtension(src)); try { File.Move(src, tmp); staged.Add(new string[] { tmp, Path.Combine(dir, plan[i][1]), src }); } catch (Exception ex) { err++; log.AppendLine(Path.GetFileName(src) + " → " + plan[i][1] + " 失败(挪到临时名这一步出错):" + ex.Message); } } foreach (string[] s in staged) { try { File.Move(s[0], s[1]); ok++; done.Add(new string[] { s[1], s[2] }); } catch (Exception ex) { err++; log.AppendLine(Path.GetFileName(s[2]) + " → " + Path.GetFileName(s[1]) + " 失败:" + ex.Message); try { if (File.Exists(s[0]) && !File.Exists(s[2])) File.Move(s[0], s[2]); } catch { } } } return new object[] { ok, err, log.ToString(), done }; } // ── 撤销上次:exe/数据目录里存 undo.json([现在的名字, 原来的名字] 对)── public static string JsonEscape(string s) { StringBuilder sb = new StringBuilder(); foreach (char c in s) { if (c == '"' || c == '\\') { sb.Append('\\'); sb.Append(c); } else if (c < ' ') sb.Append("\\u").Append(((int)c).ToString("x4")); else sb.Append(c); } return sb.ToString(); } public static void SaveUndoLog(string dir, List done) { if (done == null || done.Count == 0) return; StringBuilder sb = new StringBuilder("[\r\n"); for (int i = 0; i < done.Count; i++) { sb.Append(" [\"").Append(JsonEscape(done[i][0])) .Append("\",\"").Append(JsonEscape(done[i][1])).Append("\"]"); if (i < done.Count - 1) sb.Append(","); sb.Append("\r\n"); } sb.Append("]\r\n"); File.WriteAllText(UndoPath(dir), sb.ToString(), new UTF8Encoding(false)); } // 数据文件写在被改名的目录里(跟文件走);写不进去(只读盘等)退 %APPDATA% public static string UndoPath(string dir) { string p = Path.Combine(dir, "gt_undo.json"); if (File.Exists(p)) return p; // 已有日志,直接用,绝不覆盖探测 try { File.WriteAllText(p, "[]", new UTF8Encoding(false)); return p; } catch { string app = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "GreenToolBox"); Directory.CreateDirectory(app); string h = JsonEscape(dir).GetHashCode().ToString("x"); return Path.Combine(app, "undo_" + h + ".json"); } } public static List LoadUndoLog(string dir) { try { string p = Path.Combine(dir, "gt_undo.json"); if (!File.Exists(p)) { string app = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "GreenToolBox"); p = Path.Combine(app, "undo_" + JsonEscape(dir).GetHashCode().ToString("x") + ".json"); } if (!File.Exists(p)) return null; string text = File.ReadAllText(p, Encoding.UTF8); if (text.Length < 4) return null; // "[]" 空日志 List list = new List(); int i = 0; while (true) { i = text.IndexOf("[\"", i, StringComparison.Ordinal); if (i < 0) break; i = text.IndexOf("\"", i + 1, StringComparison.Ordinal); string a = ReadJsonStr(text, ref i); i = text.IndexOf("\"", i + 1, StringComparison.Ordinal); string b = ReadJsonStr(text, ref i); if (a != null && b != null) list.Add(new string[] { a, b }); } return list.Count > 0 ? list : null; } catch { return null; } } // 从 i 处的引号开始读一个 JSON 字符串(支持 \" \\ \uXXXX),i 停在结束引号 private static string ReadJsonStr(string s, ref int i) { if (s == null || i < 0 || i >= s.Length || s[i] != '"') return null; StringBuilder sb = new StringBuilder(); i++; while (i < s.Length) { char c = s[i]; if (c == '"') return sb.ToString(); if (c == '\\') { i++; if (i >= s.Length) break; char e = s[i]; if (e == 'n') sb.Append('\n'); else if (e == 'r') sb.Append('\r'); else if (e == 't') sb.Append('\t'); else if (e == 'u') { if (i + 4 < s.Length) sb.Append((char)Convert.ToInt32(s.Substring(i + 1, 4), 16)); i += 4; } else sb.Append(e); } else sb.Append(c); i++; } return null; } } // 命令行自测:不弹窗,纯逻辑跑一遍,退出码 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"); } 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 string Read(string p) { return File.Exists(p) ? File.ReadAllText(p, Encoding.UTF8) : ""; } public static int Run(string dir) { if (string.IsNullOrEmpty(dir)) dir = Path.Combine(Path.GetTempPath(), "greentool-rename-selftest"); string work = Path.Combine(dir, "rn"); string swap = Path.Combine(dir, "swap"); string clash = Path.Combine(dir, "clash"); string undo1 = Path.Combine(dir, "undo1"); string undo2 = Path.Combine(dir, "undo2"); string undo3 = Path.Combine(dir, "undo3"); try { Directory.CreateDirectory(dir); _lines.Add("批量重命名 自测(" + dir + ")"); // ── 查找替换 ── Check("区分大小写时不动大小写不同的部分", RenameOps.ReplaceExact("Photo", "photo", "x"), "Photo"); Check("区分大小写命中时正常替换", RenameOps.ReplaceExact("Photo_2024", "Photo", "pic"), "pic_2024"); Check("忽略大小写命中", RenameOps.ReplaceIgnoreCase("Photo_2024", "photo", "pic"), "pic_2024"); Check("每个出现都替换", RenameOps.ReplaceIgnoreCase("aaa", "a", "b"), "bbb"); Check("中文替换", RenameOps.ReplaceIgnoreCase("报告-副本-副本", "副本", ""), "报告--"); Check("查找为空时原样返回", RenameOps.ReplaceIgnoreCase("abc", "", "x"), "abc"); // ── 保留扩展名的两种语义 ── Check("保留扩展名:只改主名", RenameOps.ApplyReplace("报告 2024.docx", "2024", "2025", false, true), "报告 2025.docx"); Check("不保留扩展名:连扩展名一起替换", RenameOps.ApplyReplace("报告 2024.docx", "docx", "txt", false, false), "报告 2024.txt"); Check("不保留扩展名时不会多出一个 .docx", RenameOps.ApplyReplace("a.docx", "b", "c", false, false), "a.docx"); // ── 前后缀 / 编号 / 扩展名 / 日期 ── Check("加前缀后缀", RenameOps.ApplyFix("a.jpg", "2024_", "_终版"), "2024_a_终版.jpg"); Check("前缀后缀为空时就是原名", RenameOps.ApplyFix("a.jpg", "", ""), "a.jpg"); Check("序号补零", RenameOps.ApplyNumber("x.png", "照片", 5, 3), "照片005.png"); CheckInt("补零位数下限 1", RenameOps.ClampPad(0), 1); CheckInt("补零位数上限 9", RenameOps.ClampPad(99), 9); Check("补零位数非法时退成 1 位", RenameOps.ApplyNumber("x.png", "p", 7, 0), "p7.png"); Check("改扩展名", RenameOps.ApplyExt("a.jpg", "png"), "a.png"); Check("扩展名带点也认", RenameOps.ApplyExt("a.jpg", ".tiff"), "a.tiff"); Check("扩展名留空就转小写", RenameOps.ApplyExt("a.JPG", ""), "a.jpg"); Check("按日期加后缀", RenameOps.ApplyDate("a.jpg", new DateTime(2026, 3, 7)), "a_20260307.jpg"); // ── 预览状态 ── Check("名字没变 → 无变化", RenameOps.PreviewState("a.txt", "a.txt", false), "无变化"); Check("目标已存在 → 冲突", RenameOps.PreviewState("a.txt", "b.txt", true), "冲突!"); Check("正常 → 就绪", RenameOps.PreviewState("a.txt", "b.txt", false), "就绪"); Check("算不出新名 → 空", RenameOps.PreviewState("a.txt", null, false), ""); // ── 真改一轮:互换名字(这一步以前必然失败)── Directory.CreateDirectory(swap); File.WriteAllText(Path.Combine(swap, "a.txt"), "AAA", Encoding.UTF8); File.WriteAllText(Path.Combine(swap, "b.txt"), "BBB", Encoding.UTF8); List plan = new List(); plan.Add(new string[] { Path.Combine(swap, "a.txt"), "b.txt" }); plan.Add(new string[] { Path.Combine(swap, "b.txt"), "a.txt" }); object[] rr = RenameOps.Execute(plan); CheckInt("互换名字成功 2 个", (int)rr[0], 2); CheckInt("互换名字失败 0 个", (int)rr[1], 0); Check("a.txt 现在装的是原来的 B", Read(Path.Combine(swap, "a.txt")), "BBB"); Check("b.txt 现在装的是原来的 A", Read(Path.Combine(swap, "b.txt")), "AAA"); Check("没留下 ~gt_ 临时文件", Directory.GetFiles(swap, "~gt_*").Length.ToString(), "0"); // ── 目标已存在:不许覆盖,且要还原 ── Directory.CreateDirectory(clash); File.WriteAllText(Path.Combine(clash, "c.txt"), "C", Encoding.UTF8); File.WriteAllText(Path.Combine(clash, "d.txt"), "D", Encoding.UTF8); List plan2 = new List(); plan2.Add(new string[] { Path.Combine(clash, "c.txt"), "d.txt" }); object[] rr2 = RenameOps.Execute(plan2); CheckInt("撞名时不算成功", (int)rr2[0], 0); CheckInt("撞名时记一次失败", (int)rr2[1], 1); Check("原来的 d.txt 内容没被盖掉", Read(Path.Combine(clash, "d.txt")), "D"); Check("c.txt 被还原回来(没丢文件)", Read(Path.Combine(clash, "c.txt")), "C"); Check("失败原因写在日志里", ((string)rr2[2]).Length > 0 ? "has-log" : "empty", "has-log"); // ── 中文名 + 空格 ── Directory.CreateDirectory(work); File.WriteAllText(Path.Combine(work, "报告 2024.docx"), "x", Encoding.UTF8); List plan3 = new List(); plan3.Add(new string[] { Path.Combine(work, "报告 2024.docx"), RenameOps.ApplyReplace("报告 2024.docx", "2024", "2025", false, true) }); object[] rr3 = RenameOps.Execute(plan3); CheckInt("中文名改成功", (int)rr3[0], 1); Check("新文件存在", File.Exists(Path.Combine(work, "报告 2025.docx")) ? "yes" : "no", "yes"); Check("旧文件已不存在", File.Exists(Path.Combine(work, "报告 2024.docx")) ? "yes" : "no", "no"); // ── 2.0 正则替换 ── Check("正则:数字序列替换", RenameOps.ApplyRegex("photo123.jpg", "\\d+", "#", true), "photo#.jpg"); Check("正则:不动扩展名", RenameOps.ApplyRegex("a.b", "\\.", "_", true), "a.b"); Check("正则:勾掉不动扩展名就全名替换", RenameOps.ApplyRegex("a.b", "\\.", "_", false), "a_b"); Check("正则:非法表达式返回 null", RenameOps.ApplyRegex("a.txt", "([", "x", true), null); Check("正则:查找为空原样返回", RenameOps.ApplyRegex("a.txt", "", "x", true), "a.txt"); // ── 2.0 大小写转换 ── Check("全大写(扩展名保持)", RenameOps.ApplyCase("My Photo.JPG", 0), "MY PHOTO.JPG"); Check("全小写(扩展名保持)", RenameOps.ApplyCase("My Photo.JPG", 1), "my photo.JPG"); Check("首字母大写", RenameOps.ApplyCase("my photo.doc", 2), "My Photo.doc"); Check("首字母大写:已是小写的扩展名不动", RenameOps.ApplyCase("ABC.jpg", 2), "ABC.jpg"); Check("全小写对中文没副作用", RenameOps.ApplyCase("照片.JPG", 1), "照片.JPG"); // ── 2.0 序号步长(编号 = 起始 + 步长×序)── Check("步长 5:第 2 个 = 1+5×1", RenameOps.ApplyNumber("x.png", "p", 1 + 1 * 5, 3), "p006.png"); Check("步长 5:第 3 个 = 1+5×2", RenameOps.ApplyNumber("x.png", "p", 1 + 2 * 5, 3), "p011.png"); // ── 2.0 撤销:往返 ── Directory.CreateDirectory(undo1); File.WriteAllText(Path.Combine(undo1, "a.txt"), "A", Encoding.UTF8); File.WriteAllText(Path.Combine(undo1, "b.txt"), "B", Encoding.UTF8); List plan4 = new List(); plan4.Add(new string[] { Path.Combine(undo1, "a.txt"), "甲.txt" }); plan4.Add(new string[] { Path.Combine(undo1, "b.txt"), "乙.txt" }); object[] rr4 = RenameOps.Execute(plan4); CheckInt("撤销测试:改名成功 2 个", (int)rr4[0], 2); RenameOps.SaveUndoLog(undo1, (List)rr4[3]); List log4 = RenameOps.LoadUndoLog(undo1); CheckInt("撤销日志读回 2 条", log4 == null ? 0 : log4.Count, 2); List plan5 = new List(); foreach (string[] p in log4) plan5.Add(new string[] { p[0], Path.GetFileName(p[1]) }); object[] rr5 = RenameOps.Execute(plan5); CheckInt("撤销执行成功 2 个", (int)rr5[0], 2); Check("a.txt 回来了(内容没丢)", Read(Path.Combine(undo1, "a.txt")), "A"); Check("甲.txt 已不在", File.Exists(Path.Combine(undo1, "甲.txt")) ? "yes" : "no", "no"); Check("撤销日志文件存在", File.Exists(Path.Combine(undo1, "gt_undo.json")) ? "yes" : "no", "yes"); // ── 2.0 撤销:原名被占时必须失败且不覆盖 ── Directory.CreateDirectory(undo2); File.WriteAllText(Path.Combine(undo2, "old.txt"), "OLD", Encoding.UTF8); List plan6 = new List(); plan6.Add(new string[] { Path.Combine(undo2, "old.txt"), "new.txt" }); object[] rr6 = RenameOps.Execute(plan6); CheckInt("占名测试:改名成功 1 个", (int)rr6[0], 1); File.WriteAllText(Path.Combine(undo2, "old.txt"), "SOMEONE-ELSE", Encoding.UTF8); object[] rr7 = RenameOps.Execute( new List { new string[] { Path.Combine(undo2, "new.txt"), "old.txt" } }); CheckInt("原名被占:撤销不算成功", (int)rr7[0], 0); Check("占位的 old.txt 内容没被覆盖", Read(Path.Combine(undo2, "old.txt")), "SOMEONE-ELSE"); Check("new.txt 还在(还原成功)", Read(Path.Combine(undo2, "new.txt")), "OLD"); // ── 2.0 撤销日志:空目录 / 坏文件 ── Directory.CreateDirectory(undo3); Check("没有日志返回 null", RenameOps.LoadUndoLog(undo3) == null ? "null" : "has", "null"); File.WriteAllText(Path.Combine(undo3, "gt_undo.json"), "[]", Encoding.UTF8); Check("空日志返回 null", RenameOps.LoadUndoLog(undo3) == null ? "null" : "has", "null"); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } finally { try { if (Directory.Exists(swap)) Directory.Delete(swap, true); } catch { } try { if (Directory.Exists(clash)) Directory.Delete(clash, true); } catch { } try { if (Directory.Exists(work)) Directory.Delete(work, true); } catch { } try { if (Directory.Exists(undo1)) Directory.Delete(undo1, true); } catch { } try { if (Directory.Exists(undo2)) Directory.Delete(undo2, true); } catch { } try { if (Directory.Exists(undo3)) Directory.Delete(undo3, true); } catch { } } _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-rename.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); RenameToolForm form = new RenameToolForm(); // 可选:exe <文件夹> [查找] [替换] 启动即扫描并预填规则① if (args != null && args.Length > 0 && Directory.Exists(args[0])) form.SetFolder(args[0]); if (args != null && args.Length >= 3) form.PrefillReplace(args[1], args[2]); Application.Run(form); } } }