// 重复文件查找 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法(net48 自带 csc 可编译) // 功能:按「体积 → 头尾摘要 → SHA1」三级筛重,找出内容完全相同的文件组 // 安全策略:不直接删除,把多余副本移到「重复文件」子文件夹,随时可以搬回来 using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.IO; using System.Security.Cryptography; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public class DupOps { public class Group { public List Files = new List(); public long Length; public string Sha1; } public class Result { public List Groups = new List(); public int Scanned; public long WastedBytes; // 可释放体积 = 组大小 × (份数-1) public List Errors = new List(); } /* headTail 摘要:头 8KB + 尾 8KB + 长度。大文件先比这个,绝大多数不等就此打住 */ public static string HeadTail(string file) { using (FileStream fs = File.OpenRead(file)) using (SHA1 sha = SHA1.Create()) { byte[] head = new byte[8192]; byte[] tail = new byte[8192]; int hn = fs.Read(head, 0, head.Length); long len = fs.Length; int tn = 0; if (len > head.Length) { fs.Seek(-Math.Min(8192L, len), SeekOrigin.End); tn = fs.Read(tail, 0, tail.Length); } byte[] buf = new byte[hn + tn + 8]; Array.Copy(head, buf, hn); Array.Copy(tail, 0, buf, hn, tn); byte[] lb = BitConverter.GetBytes(len); Array.Copy(lb, 0, buf, hn + tn, 8); return Hex(sha.ComputeHash(buf)); } } public static string Sha1File(string file) { using (FileStream fs = File.OpenRead(file)) using (SHA1 sha = SHA1.Create()) { return Hex(sha.ComputeHash(fs)); } } public static string Hex(byte[] b) { StringBuilder sb = new StringBuilder(b.Length * 2); for (int i = 0; i < b.Length; i++) sb.Append(b[i].ToString("x2")); return sb.ToString(); } public static List WalkFiles(string root, Result r) { List all = new List(); Walk(new DirectoryInfo(root), all, r); return all; } private static void Walk(DirectoryInfo di, List all, Result r) { try { foreach (FileInfo f in di.GetFiles()) { // 0 字节文件都「相同」,列出来只会刷屏,跳过 if (f.Length == 0) continue; all.Add(f.FullName); r.Scanned++; } foreach (DirectoryInfo sd in di.GetDirectories()) { if ((sd.Attributes & FileAttributes.ReparsePoint) != 0) continue; Walk(sd, all, r); } } catch (Exception ex) { r.Errors.Add("进不去:" + di.FullName + "(" + ex.GetType().Name + ")"); } } public static Result Find(string root) { if (!Directory.Exists(root)) throw new IOException("目录不存在:" + root); Result r = new Result(); // 1) 体积分桶 Dictionary> byLen = new Dictionary>(); foreach (string f in WalkFiles(root, r)) { long len; try { len = new FileInfo(f).Length; } catch { r.Errors.Add("读不到:" + f); continue; } if (!byLen.ContainsKey(len)) byLen[len] = new List(); byLen[len].Add(f); } // 2) 头尾摘要分桶,3) 全量 SHA1 确认 foreach (KeyValuePair> kv in byLen) { if (kv.Value.Count < 2) continue; Dictionary> byHT = new Dictionary>(); foreach (string f in kv.Value) { try { string ht = HeadTail(f); if (!byHT.ContainsKey(ht)) byHT[ht] = new List(); byHT[ht].Add(f); } catch { r.Errors.Add("读不了:" + f); } } foreach (KeyValuePair> g in byHT) { if (g.Value.Count < 2) continue; Dictionary> bySha = new Dictionary>(); foreach (string f in g.Value) { try { string sha = Sha1File(f); if (!bySha.ContainsKey(sha)) bySha[sha] = new List(); bySha[sha].Add(f); } catch { r.Errors.Add("读不了:" + f); } } foreach (KeyValuePair> fg in bySha) { if (fg.Value.Count < 2) continue; Group grp = new Group(); grp.Files = fg.Value; grp.Length = kv.Key; grp.Sha1 = fg.Key; r.Groups.Add(grp); r.WastedBytes += kv.Key * (fg.Value.Count - 1); } } } r.Groups.Sort(delegate(Group a, Group b) { return b.Length.CompareTo(a.Length); }); return r; } /* 把每组里「保留最新的一个」以外的副本移到 root\重复文件\。 同名冲突:前缀 (2)(3)。返回 (移动数, 报告行)。绝不删除。 */ public static List MoveDuplicates(Result r, string root, out int moved) { moved = 0; List report = new List(); string dest = Path.Combine(root, "重复文件"); Directory.CreateDirectory(dest); foreach (Group g in r.Groups) { // 保留「修改时间最新」的;同秒的按全名排序取第一个,保证确定性 List sorted = new List(g.Files); sorted.Sort(delegate(string a, string b) { int c = File.GetLastWriteTime(b).CompareTo(File.GetLastWriteTime(a)); return c != 0 ? c : string.CompareOrdinal(a, b); }); for (int i = 1; i < sorted.Count; i++) { string src = sorted[i]; // 已经在「重复文件」里的文件不再搬(重复点一次移动会撞上自己) if (IsUnder(src, dest)) continue; string name = Path.GetFileName(src); string target = Path.Combine(dest, name); int k = 2; while (File.Exists(target)) { target = Path.Combine(dest, Path.GetFileNameWithoutExtension(name) + " (" + k + ")" + Path.GetExtension(name)); k++; } try { File.Move(src, target); moved++; report.Add(Path.GetFileName(sorted[0]) + " 保留 ← " + src + " → " + target); } catch (Exception ex) { report.Add("移动失败:" + src + "(" + ex.Message + ")"); } } } return report; } static bool IsUnder(string file, string dir) { string f = Path.GetFullPath(file).TrimEnd('\\') + "\\"; string d = Path.GetFullPath(dir).TrimEnd('\\') + "\\"; return f.StartsWith(d, StringComparison.OrdinalIgnoreCase); } public static string FormatSize(long b) { if (b < 1024) return b + " B"; double v = b; string[] u = new string[] { "KB", "MB", "GB", "TB" }; int i = -1; while (v >= 1024 && i < u.Length - 1) { v /= 1024; i++; } return v.ToString(i == 0 ? "0" : "0.0") + " " + u[i]; } } public class DupFinderForm : Form { private TextBox txtDir; private Button btnPick; private Button btnScan; private Button btnMove; private Button btnExport; private ListView lv; private Label lblStatus; private ProgressBar progress; private BackgroundWorker worker; private DupOps.Result last; private string lastRoot = ""; public DupFinderForm() { InitUi(); worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; 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(780, 560); this.MinimumSize = new Size(680, 480); this.AllowDrop = true; this.DragEnter += new DragEventHandler(FormDragEnter); this.DragDrop += new DragEventHandler(FormDragDrop); int x = 20, y = 16; Label lblTitle = new Label(); lblTitle.Text = "找出内容完全相同的文件;不直接删除,多余副本移到「重复文件」文件夹,随时可搬回来"; 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(600, 26); this.Controls.Add(txtDir); btnPick = new Button(); btnPick.Text = "浏览…"; btnPick.Location = new Point(630, y - 1); btnPick.Size = new Size(130, 28); btnPick.Click += new EventHandler(PickClick); this.Controls.Add(btnPick); y += 42; btnScan = new Button(); btnScan.Text = "开始查找"; btnScan.Location = new Point(x, y); btnScan.Size = new Size(140, 34); btnScan.BackColor = Color.FromArgb(0, 145, 88); btnScan.ForeColor = Color.White; btnScan.FlatStyle = FlatStyle.Flat; btnScan.Click += new EventHandler(ScanClick); this.Controls.Add(btnScan); btnMove = new Button(); btnMove.Text = "清理多余副本"; btnMove.Location = new Point(x + 156, y); btnMove.Size = new Size(150, 34); btnMove.Enabled = false; btnMove.Click += new EventHandler(MoveClick); this.Controls.Add(btnMove); btnExport = new Button(); btnExport.Text = "导出清单 (txt)"; btnExport.Location = new Point(x + 322, y); btnExport.Size = new Size(150, 34); btnExport.Enabled = false; btnExport.Click += new EventHandler(ExportClick); this.Controls.Add(btnExport); progress = new ProgressBar(); progress.Location = new Point(490, y + 6); progress.Size = new Size(270, 20); progress.Style = ProgressBarStyle.Marquee; progress.MarqueeAnimationSpeed = 40; progress.Visible = false; this.Controls.Add(progress); y += 52; 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(740, 380); lv.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; lv.Columns.Add("组", 44); lv.Columns.Add("大小", 90, HorizontalAlignment.Right); lv.Columns.Add("份数", 52, HorizontalAlignment.Right); lv.Columns.Add("文件(每组保留最新的一个,其余是多余副本)", 520); lv.DoubleClick += new EventHandler(LvOpen); 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 void ScanClick(object sender, EventArgs e) { string dir = (txtDir.Text ?? "").Trim(); if (dir.Length == 0 || !Directory.Exists(dir)) { lblStatus.Text = "先选一个存在的目录。"; lblStatus.ForeColor = Color.FromArgb(200, 50, 50); return; } btnScan.Enabled = false; btnMove.Enabled = false; btnExport.Enabled = false; progress.Visible = true; worker.RunWorkerAsync(dir); } private void WorkerDoWork(object sender, DoWorkEventArgs e) { e.Result = DupOps.Find((string)e.Argument); } private void WorkerDone(object sender, RunWorkerCompletedEventArgs e) { btnScan.Enabled = true; progress.Visible = false; if (e.Error != null) { lblStatus.Text = "查找失败:" + e.Error.Message; lblStatus.ForeColor = Color.FromArgb(200, 50, 50); return; } last = (DupOps.Result)e.Result; lastRoot = txtDir.Text.Trim(); lv.BeginUpdate(); lv.Items.Clear(); for (int i = 0; i < last.Groups.Count; i++) { DupOps.Group g = last.Groups[i]; ListViewItem li = new ListViewItem((i + 1).ToString()); li.SubItems.Add(DupOps.FormatSize(g.Length)); li.SubItems.Add(g.Files.Count.ToString()); li.SubItems.Add(string.Join(" = ", g.Files.ToArray())); li.Tag = g; lv.Items.Add(li); } lv.EndUpdate(); lblStatus.ForeColor = last.Groups.Count > 0 ? Color.FromArgb(0, 145, 88) : Color.FromArgb(120, 130, 124); lblStatus.Text = last.Groups.Count == 0 ? "扫了 " + last.Scanned + " 个文件,没发现重复" : "发现 " + last.Groups.Count + " 组重复,可释放 " + DupOps.FormatSize(last.WastedBytes) + (last.Errors.Count > 0 ? "(" + last.Errors.Count + " 项跳过)" : ""); btnMove.Enabled = last.Groups.Count > 0; btnExport.Enabled = true; } private void LvOpen(object sender, EventArgs e) { if (lv.SelectedItems.Count == 0) return; DupOps.Group g = lv.SelectedItems[0].Tag as DupOps.Group; if (g != null && g.Files.Count > 0) { System.Diagnostics.Process.Start("explorer.exe", "/select,\"" + g.Files[0] + "\""); } } private void MoveClick(object sender, EventArgs e) { if (last == null || last.Groups.Count == 0) return; DialogResult dr = MessageBox.Show(this, "每组保留「修改时间最新」的一份,其余移到:\n" + Path.Combine(lastRoot, "重复文件") + "\n\n不会删除任何文件。继续?", "清理多余副本", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if (dr != DialogResult.OK) return; int moved; List report = DupOps.MoveDuplicates(last, lastRoot, out moved); lblStatus.ForeColor = Color.FromArgb(0, 145, 88); lblStatus.Text = "已移动 " + moved + " 个副本到「重复文件」文件夹。重新查找可以验证。"; btnMove.Enabled = false; MessageBox.Show(this, moved + " 个副本已移动。\n\n" + (report.Count > 12 ? string.Join("\n", report.GetRange(0, 12).ToArray()) + "\n…详见导出清单" : string.Join("\n", report.ToArray())), "完成", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void ExportClick(object sender, EventArgs e) { if (last == null) return; SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "文本文件 (*.txt)|*.txt"; dlg.FileName = "重复文件清单_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".txt"; if (dlg.ShowDialog(this) != DialogResult.OK) return; StringBuilder sb = new StringBuilder(); sb.AppendLine("重复文件查找报告 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); sb.AppendLine("目录:" + lastRoot); sb.AppendLine("扫描 " + last.Scanned + " 个文件," + last.Groups.Count + " 组重复,可释放 " + DupOps.FormatSize(last.WastedBytes)); sb.AppendLine(); for (int i = 0; i < last.Groups.Count; i++) { DupOps.Group g = last.Groups[i]; sb.AppendLine("第 " + (i + 1) + " 组|" + DupOps.FormatSize(g.Length) + " × " + g.Files.Count + " 份|SHA1 " + g.Sha1); foreach (string f in g.Files) sb.AppendLine(" " + f); } if (last.Errors.Count > 0) { sb.AppendLine(); foreach (string er in last.Errors) sb.AppendLine("跳过:" + er); } File.WriteAllText(dlg.FileName, sb.ToString(), new UTF8Encoding(true)); lblStatus.Text = "清单已保存:" + dlg.FileName; } } // ───────────────────────── 自测 ───────────────────────── public static class DupSelfTest { 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); } } 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-dup-" + Guid.NewGuid().ToString("N").Substring(0, 8)) : dir; try { Directory.CreateDirectory(baseDir); byte[] contentA = new byte[100 * 1024 + 123]; // >16KB,跨过头尾摘要 for (int i = 0; i < contentA.Length; i++) contentA[i] = (byte)(i * 7); byte[] contentB = new byte[50 * 1024]; for (int i = 0; i < contentB.Length; i++) contentB[i] = (byte)(255 - i); // a 组 3 份(跨子目录),b 组 2 份,独苗 1 个,0 字节 1 个(应跳过) File.WriteAllBytes(Path.Combine(baseDir, "a1.img"), contentA); Directory.CreateDirectory(Path.Combine(baseDir, "备份")); File.WriteAllBytes(Path.Combine(baseDir, "备份", "a2.img"), contentA); Directory.CreateDirectory(Path.Combine(baseDir, "备份", "更深层")); File.WriteAllBytes(Path.Combine(baseDir, "备份", "更深层", "a3-copy.img"), contentA); File.WriteAllBytes(Path.Combine(baseDir, "b1.doc"), contentB); File.WriteAllBytes(Path.Combine(baseDir, "b2.doc"), contentB); File.WriteAllBytes(Path.Combine(baseDir, "unique.txt"), new byte[99]); File.WriteAllBytes(Path.Combine(baseDir, "empty.dat"), new byte[0]); // 差一个字节的「近重复」:绝不能判成相同 byte[] contentA2 = (byte[])contentA.Clone(); contentA2[contentA2.Length - 1] ^= 0xFF; File.WriteAllBytes(Path.Combine(baseDir, "a4-almost.img"), contentA2); DupOps.Result r = DupOps.Find(baseDir); Check("组数", r.Groups.Count, 2); Check("扫描数(不含空文件)", r.Scanned, 7); Check("无错误", r.Errors.Count, 0); DupOps.Group big = r.Groups[0]; // 4 张 a 内容的图里,a4-almost 故意差一个字节,正确结果只收 3 份 Check("最大的组是 a 组(3 份,近重复不算)", big.Files.Count, 3); Check("a 组体积", big.Length, (long)contentA.Length); Check("a 组 SHA1 一致", big.Sha1, DupOps.Sha1File(Path.Combine(baseDir, "a1.img"))); // 头尾摘要:同内容必同摘要;差一字节不同摘要(含长度段) Check("头尾摘要区分近重复", DupOps.HeadTail(Path.Combine(baseDir, "a1.img")) == DupOps.HeadTail(Path.Combine(baseDir, "a4-almost.img")), false); // 清理:a 组 3 份留 1 移 2,b 组 2 份留 1 移 1 → 共移 3 个 int moved; List report = DupOps.MoveDuplicates(r, baseDir, out moved); Check("移动数", moved, 3); string dupDir = Path.Combine(baseDir, "重复文件"); Check("目标目录已建", Directory.Exists(dupDir), true); Check("移动的文件都在「重复文件」里", Directory.GetFiles(dupDir, "*", SearchOption.AllDirectories).Length, 3); Check("报告有 3 行", report.Count, 3); // 同名冲突:目标里已有 x.img,再移两个同名进来 → (2) (3) string cd1 = Path.Combine(baseDir, "c1"); Directory.CreateDirectory(cd1); File.WriteAllBytes(Path.Combine(cd1, "x.img"), contentB); Directory.CreateDirectory(Path.Combine(baseDir, "conflict")); File.WriteAllBytes(Path.Combine(baseDir, "conflict", "x.img"), contentB); File.WriteAllBytes(Path.Combine(dupDir, "x.img"), contentB); // 占位:同内容才进同组 File.SetLastWriteTime(Path.Combine(dupDir, "x.img"), new DateTime(2030, 1, 1)); File.WriteAllText(Path.Combine(dupDir, "占位.txt"), "x"); // 非 x.img,不影响 DupOps.Result rc = DupOps.Find(baseDir); DupOps.Group xg = rc.Groups.Find(delegate(DupOps.Group g) { return g.Files.Exists(delegate(string s) { return s.EndsWith("x.img"); }); }); Check("同名组找到(5 份:b1/b2/x 占位/两个新的)", xg.Files.Count, 5); DupOps.MoveDuplicates(rc, baseDir, out moved); Check("冲突改名成 (2)", File.Exists(Path.Combine(dupDir, "x (2).img")), true); Check("冲突改名成 (3)", File.Exists(Path.Combine(dupDir, "x (3).img")), true); Check("目标目录里 x 系列共 3 个", Directory.GetFiles(dupDir, "x*.img").Length, 3); // 清场后再查:0 组 Directory.Delete(dupDir, true); DupOps.Result r2 = DupOps.Find(baseDir); Check("清理后重查为 0 组", r2.Groups.Count, 0); // 不存在的目录要报错 bool threw = false; try { DupOps.Find(Path.Combine(baseDir, "no-such")); } catch { threw = true; } Check("目录不存在抛异常", threw ? "threw" : "silent", "threw"); } 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-dupfinder.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(DupSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new DupFinderForm()); } } }