// 空文件夹清理 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法 // 功能:找出空文件夹(含「只装着空文件夹」的父目录)和零字节文件;默认移到备份目录可还原,也可直接删除 // 边界:不跟随符号链接/junction;跳过系统目录;只处理本机磁盘,不联网 // 安全:默认「移到备份」而非删除,并记 manifest.txt 可一键还原;直接删除需二次确认 using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public class CleanOptions { public bool IncludeZeroFiles = true; public bool IncludeHidden = false; public bool KeepRoot = true; } public class CleanItem { public string Path; public bool IsDir; public long Size; public override string ToString() { return Path; } } public static class CleanOps { // 系统/版本库目录一律不碰,避免误伤 public static bool IsIgnoredName(string name) { if (string.IsNullOrEmpty(name)) return true; string[] bad = new string[] { "$RECYCLE.BIN", "System Volume Information", "Recovery", "Config.Msi", ".git", ".svn", ".hg", "node_modules", ".venv", "Windows", "WinSxS" }; foreach (string b in bad) if (string.Equals(name, b, StringComparison.OrdinalIgnoreCase)) return true; return false; } static bool IsHiddenOrSystem(FileSystemInfo f) { try { FileAttributes a = f.Attributes; return (a & FileAttributes.Hidden) != 0 || (a & FileAttributes.System) != 0; } catch { return false; } } static bool IsLink(FileSystemInfo f) { try { return (f.Attributes & FileAttributes.ReparsePoint) != 0; } catch { return true; } } // 递归扫描。返回结果按「深度降序」排好,删除时子项先于父项 public static List Scan(string root, CleanOptions opt) { List found = new List(); if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) return found; if (opt == null) opt = new CleanOptions(); WalkDir(new DirectoryInfo(root), opt, found, true); found.Sort(delegate(CleanItem a, CleanItem b) { int da = Depth(a.Path), db = Depth(b.Path); if (da != db) return db.CompareTo(da); return string.Compare(a.Path, b.Path, StringComparison.OrdinalIgnoreCase); }); return found; } public static int Depth(string path) { if (string.IsNullOrEmpty(path)) return 0; int n = 0; foreach (char c in path) if (c == '\\' || c == '/') n++; return n; } // 返回:这个目录(清理后)是否为空 static bool WalkDir(DirectoryInfo dir, CleanOptions opt, List found, bool isRoot) { bool empty = true; FileSystemInfo[] children; try { children = dir.GetFileSystemInfos(); } catch { return false; } // 没权限就当非空,避免误删 foreach (FileSystemInfo c in children) { if (IsLink(c)) { empty = false; continue; } if (!opt.IncludeHidden && IsHiddenOrSystem(c)) { empty = false; continue; } DirectoryInfo sub = c as DirectoryInfo; if (sub != null) { if (IsIgnoredName(sub.Name)) { empty = false; continue; } bool subEmpty = WalkDir(sub, opt, found, false); // 这里处理的永远是「子目录」,根目录本身不会进这个分支,所以直接记录 if (subEmpty) found.Add(new CleanItem { Path = sub.FullName, IsDir = true }); else empty = false; } else { FileInfo fi = c as FileInfo; if (fi == null) { empty = false; continue; } if (fi.Length == 0 && opt.IncludeZeroFiles && !IsIgnoredName(fi.Name)) { found.Add(new CleanItem { Path = fi.FullName, IsDir = false, Size = 0 }); // 零字节文件被清理后,这个目录也变空了 } else empty = false; } } return empty; } public static string SizeText(long b) { if (b < 1024) return b + " B"; if (b < 1024 * 1024) return (b / 1024.0).ToString("0.0") + " KB"; if (b < 1024L * 1024 * 1024) return (b / 1024.0 / 1024.0).ToString("0.0") + " MB"; return (b / 1024.0 / 1024.0 / 1024.0).ToString("0.00") + " GB"; } public static string RelPath(string root, string full) { string r = Path.GetFullPath(root).TrimEnd('\\', '/'); string f = Path.GetFullPath(full); if (f.StartsWith(r, StringComparison.OrdinalIgnoreCase)) { string tail = f.Substring(r.Length).TrimStart('\\', '/'); return tail.Length == 0 ? "." : tail; } return f; } // 移到备份目录,返回实际备份路径;manifest 记录原路径 public static string MoveToBackup(string root, CleanItem it, string backupRoot, StringBuilder manifest) { string rel = RelPath(root, it.Path); string safe = rel.Replace('\\', '_').Replace('/', '_'); if (safe == ".") safe = "根目录"; string dest = Path.Combine(backupRoot, (it.IsDir ? "目录_" : "文件_") + safe); int n = 2; while (File.Exists(dest) || Directory.Exists(dest)) { dest = Path.Combine(backupRoot, (it.IsDir ? "目录_" : "文件_") + safe + "_" + n); n++; } if (it.IsDir) Directory.Move(it.Path, dest); else File.Move(it.Path, dest); if (manifest != null) manifest.AppendLine(it.Path + "\t" + dest + "\t" + (it.IsDir ? "dir" : "file")); return dest; } // 直接删除:目录必须已经空了(自底向上排序保证这一点) public static bool DeleteNow(CleanItem it, out string err) { err = ""; try { if (it.IsDir) Directory.Delete(it.Path, false); else File.Delete(it.Path); return true; } catch (Exception ex) { err = ex.Message; return false; } } public static string NewBackupDir(string root) { string parent = Directory.GetParent(Path.GetFullPath(root)) != null ? Directory.GetParent(Path.GetFullPath(root)).FullName : Path.GetFullPath(root); string baseName = "空目录备份_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"); string d = Path.Combine(parent, baseName); int i = 2; while (Directory.Exists(d)) { d = Path.Combine(parent, baseName + "_" + i); i++; } Directory.CreateDirectory(d); return d; } // 还原:按 manifest 倒序(父项后还原,先有父目录再放子项) public static int Restore(string manifestPath, out string err) { err = ""; if (!File.Exists(manifestPath)) { err = "找不到 manifest.txt"; return 0; } List rows = new List(); foreach (string line in File.ReadAllLines(manifestPath, Encoding.UTF8)) { if (line.Trim().Length == 0) continue; string[] p = line.Split('\t'); if (p.Length < 3) continue; rows.Add(p); } int ok = 0; for (int i = rows.Count - 1; i >= 0; i--) { string[] p = rows[i]; try { string src = p[1], dst = p[0]; string parent = Path.GetDirectoryName(dst); if (!string.IsNullOrEmpty(parent)) Directory.CreateDirectory(parent); if (p[2] == "dir") { if (Directory.Exists(src)) { if (!Directory.Exists(dst)) Directory.Move(src, dst); else Directory.Delete(src, true); ok++; } } else if (File.Exists(src)) { if (File.Exists(dst)) dst = Path.Combine(parent, Path.GetFileNameWithoutExtension(dst) + " (还原)" + Path.GetExtension(dst)); File.Move(src, dst); ok++; } } catch { } } return ok; } } public class CleanForm : Form { TextBox _root; Button _browse, _scan, _backup, _delete, _restore, _openBak; CheckBox _zeroFiles, _hidden; ListView _list; Label _status; List _items = new List(); string _rootPath = ""; string _lastBackup = ""; public CleanForm() { Text = "空文件夹清理 - 绿色工具箱"; ClientSize = new Size(760, 560); MinimumSize = new Size(680, 500); StartPosition = FormStartPosition.CenterScreen; Font = new Font("Microsoft YaHei UI", 9f); BackColor = Color.White; Label title = new Label(); title.Text = "空文件夹清理"; title.Font = new Font("Microsoft YaHei UI", 14f, FontStyle.Bold); title.SetBounds(16, 12, 300, 30); Label hint = new Label(); hint.Text = "只清理真正空的目录和 0 字节文件;默认移到备份目录,随时可还原。"; hint.ForeColor = Color.FromArgb(110, 110, 110); hint.SetBounds(16, 44, 640, 20); Label lb = new Label(); lb.Text = "扫描目录"; lb.SetBounds(16, 76, 60, 22); _root = new TextBox(); _root.SetBounds(80, 73, 500, 26); _browse = new Button(); _browse.Text = "浏览…"; _browse.SetBounds(590, 72, 70, 28); _browse.Click += delegate { using (FolderBrowserDialog d = new FolderBrowserDialog()) { d.Description = "选择要清理的磁盘或文件夹"; if (d.ShowDialog(this) == DialogResult.OK) _root.Text = d.SelectedPath; } }; _scan = new Button(); _scan.Text = "开始扫描"; _scan.SetBounds(668, 72, 84, 28); _scan.Click += delegate { DoScan(); }; _zeroFiles = new CheckBox(); _zeroFiles.Text = "同时清理 0 字节文件"; _zeroFiles.Checked = true; _zeroFiles.SetBounds(80, 108, 180, 22); _hidden = new CheckBox(); _hidden.Text = "把隐藏文件也算内容(不建议)"; _hidden.SetBounds(270, 108, 240, 22); _list = new ListView(); _list.View = View.Details; _list.FullRowSelect = true; _list.CheckBoxes = true; _list.GridLines = false; _list.SetBounds(16, 140, 728, 330); _list.Columns.Add("", 30); _list.Columns.Add("类型", 70); _list.Columns.Add("路径", 560); _list.Columns.Add("大小", 60); _status = new Label(); _status.SetBounds(16, 482, 300, 24); _status.Text = "待机"; _status.ForeColor = Color.FromArgb(110, 110, 110); _backup = new Button(); _backup.Text = "移到备份(推荐)"; _backup.SetBounds(16, 510, 160, 38); _backup.BackColor = Color.FromArgb(37, 148, 92); _backup.ForeColor = Color.White; _backup.FlatStyle = FlatStyle.Flat; _backup.Font = new Font("Microsoft YaHei UI", 10f, FontStyle.Bold); _backup.Click += delegate { DoRemove(true); }; _delete = new Button(); _delete.Text = "直接删除"; _delete.SetBounds(186, 510, 110, 38); _delete.Click += delegate { DoRemove(false); }; _restore = new Button(); _restore.Text = "从备份还原…"; _restore.SetBounds(306, 510, 130, 38); _restore.Click += delegate { DoRestore(); }; _openBak = new Button(); _openBak.Text = "打开备份目录"; _openBak.SetBounds(446, 510, 130, 38); _openBak.Click += delegate { if (string.IsNullOrEmpty(_lastBackup) || !Directory.Exists(_lastBackup)) { MessageBox.Show("还没有备份目录。", "提示"); return; } System.Diagnostics.Process.Start("explorer.exe", "\"" + _lastBackup + "\""); }; Controls.Add(title); Controls.Add(hint); Controls.Add(lb); Controls.Add(_root); Controls.Add(_browse); Controls.Add(_scan); Controls.Add(_zeroFiles); Controls.Add(_hidden); Controls.Add(_list); Controls.Add(_status); Controls.Add(_backup); Controls.Add(_delete); Controls.Add(_restore); Controls.Add(_openBak); // 停靠布局按 z-order 逆序计算:列表最先布局 Controls.SetChildIndex(_list, 0); Controls.SetChildIndex(_status, 1); Controls.SetChildIndex(_openBak, 2); Controls.SetChildIndex(_restore, 3); Controls.SetChildIndex(_delete, 4); Controls.SetChildIndex(_backup, 5); } void DoScan() { string root = _root.Text.Trim(); if (root.Length == 0 || !Directory.Exists(root)) { MessageBox.Show("请选择一个存在的目录。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } _rootPath = Path.GetFullPath(root); CleanOptions opt = new CleanOptions(); opt.IncludeZeroFiles = _zeroFiles.Checked; opt.IncludeHidden = _hidden.Checked; opt.KeepRoot = true; Cursor = Cursors.WaitCursor; try { _items = CleanOps.Scan(_rootPath, opt); } finally { Cursor = Cursors.Default; } _list.BeginUpdate(); _list.Items.Clear(); int dirs = 0, files = 0; foreach (CleanItem it in _items) { ListViewItem li = new ListViewItem(""); li.Checked = true; li.SubItems.Add(it.IsDir ? "空文件夹" : "0 字节文件"); li.SubItems.Add(it.Path); li.SubItems.Add(it.IsDir ? "-" : "0 B"); li.Tag = it; _list.Items.Add(li); if (it.IsDir) dirs++; else files++; } _list.EndUpdate(); _status.Text = "扫描完成:" + dirs + " 个空文件夹," + files + " 个 0 字节文件"; } List Checked() { List r = new List(); foreach (ListViewItem li in _list.Items) if (li.Checked) r.Add((CleanItem)li.Tag); return r; } void DoRemove(bool toBackup) { List sel = Checked(); if (sel.Count == 0) { MessageBox.Show("列表里没有要清理的项目。", "提示"); return; } if (!toBackup) { DialogResult d = MessageBox.Show( "将永久删除 " + sel.Count + " 项,删了没法恢复。\r\n\r\n确定吗?", "直接删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2); if (d != DialogResult.Yes) return; } // 深度降序:子目录先处理,父目录才真的空 sel.Sort(delegate(CleanItem a, CleanItem b) { return CleanOps.Depth(b.Path).CompareTo(CleanOps.Depth(a.Path)); }); string backupDir = null; StringBuilder manifest = new StringBuilder(); if (toBackup) { try { backupDir = CleanOps.NewBackupDir(_rootPath); } catch (Exception ex) { MessageBox.Show("建备份目录失败:" + ex.Message, "提示"); return; } _lastBackup = backupDir; } int ok = 0, fail = 0; StringBuilder errs = new StringBuilder(); foreach (CleanItem it in sel) { if (toBackup) { try { CleanOps.MoveToBackup(_rootPath, it, backupDir, manifest); ok++; } catch (Exception ex) { fail++; errs.AppendLine(it.Path + ":" + ex.Message); } } else { string err; if (CleanOps.DeleteNow(it, out err)) ok++; else { fail++; errs.AppendLine(it.Path + ":" + err); } } } if (toBackup && manifest.Length > 0) { try { File.WriteAllText(Path.Combine(backupDir, "manifest.txt"), manifest.ToString(), new UTF8Encoding(false)); } catch { } } _status.Text = (toBackup ? "已移到备份 " : "已删除 ") + ok + (fail > 0 ? ",失败 " + fail : ""); if (fail > 0) MessageBox.Show("有 " + fail + " 项没处理成(可能被占用或没权限):\r\n" + errs.ToString(), "结果", MessageBoxButtons.OK, MessageBoxIcon.Warning); else if (toBackup) MessageBox.Show("已移到备份 " + ok + " 项。\r\n备份位置:\r\n" + backupDir + "\r\n\r\n想反悔就点「从备份还原」。", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information); else MessageBox.Show("已删除 " + ok + " 项。", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information); DoScan(); } void DoRestore() { using (OpenFileDialog d = new OpenFileDialog()) { d.Title = "选择备份目录里的 manifest.txt"; d.Filter = "备份清单|manifest.txt|所有文件|*.*"; if (!string.IsNullOrEmpty(_lastBackup) && File.Exists(Path.Combine(_lastBackup, "manifest.txt"))) d.InitialDirectory = _lastBackup; if (d.ShowDialog(this) != DialogResult.OK) return; string err; int n = CleanOps.Restore(d.FileName, out err); if (err.Length > 0) MessageBox.Show(err, "提示"); else MessageBox.Show("已还原 " + n + " 项。", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information); DoScan(); } } } public static class CleanSelfTest { 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 root = string.IsNullOrEmpty(dir) ? Path.Combine(Path.GetTempPath(), "gt-clean") : dir; try { if (Directory.Exists(root)) Directory.Delete(root, true); Directory.CreateDirectory(root); // 造数据 Directory.CreateDirectory(Path.Combine(root, "空1")); Directory.CreateDirectory(Path.Combine(root, "嵌套", "空2")); Directory.CreateDirectory(Path.Combine(root, "有货")); File.WriteAllText(Path.Combine(root, "有货", "x.txt"), "12345", new UTF8Encoding(false)); File.WriteAllBytes(Path.Combine(root, "零.bin"), new byte[0]); File.WriteAllText(Path.Combine(root, "正常.txt"), "abc", new UTF8Encoding(false)); Directory.CreateDirectory(Path.Combine(root, "藏着")); File.WriteAllBytes(Path.Combine(root, "藏着", "z.dat"), new byte[0]); CleanOptions opt = new CleanOptions(); opt.IncludeZeroFiles = true; opt.IncludeHidden = false; List items = CleanOps.Scan(root, opt); int dirs = 0, files = 0; foreach (CleanItem it in items) { if (it.IsDir) dirs++; else files++; } Check("空目录数量(空1 / 嵌套空2 / 嵌套本身 / 藏着)", dirs, 4); Check("0 字节文件数量", files, 2); Check("根目录不在结果里", Has(items, root), false); Check("有货不是空的", Has(items, Path.Combine(root, "有货")), false); Check("零字节清掉后藏着也变空", Has(items, Path.Combine(root, "藏着")), true); Check("正常文件不在结果里", Has(items, Path.Combine(root, "正常.txt")), false); // 深度降序:嵌套\空2 必须排在 嵌套 之前 int iDeep = IndexOf(items, Path.Combine(root, "嵌套", "空2")); int iParent = IndexOf(items, Path.Combine(root, "嵌套")); Check("子目录排在父目录之前", iDeep < iParent, true); // 排除零字节文件后,藏着不再是空的 CleanOptions opt2 = new CleanOptions(); opt2.IncludeZeroFiles = false; List items2 = CleanOps.Scan(root, opt2); Check("不清理零字节时不报藏着", Has(items2, Path.Combine(root, "藏着")), false); Check("不清理零字节时文件数 0", CountFiles(items2), 0); // 系统目录名判断 Check("跳过 .git", CleanOps.IsIgnoredName(".git"), true); Check("跳过 node_modules", CleanOps.IsIgnoredName("node_modules"), true); Check("普通名字不跳过", CleanOps.IsIgnoredName("我的资料"), false); // 相对路径 Check("相对路径", CleanOps.RelPath(root, Path.Combine(root, "空1")), "空1"); Check("相对路径带层", CleanOps.RelPath(root, Path.Combine(root, "嵌套", "空2")), "嵌套\\空2"); Check("根自身相对路径", CleanOps.RelPath(root, root), "."); // 备份 → 还原 string bak = CleanOps.NewBackupDir(root); Check("备份目录已建", Directory.Exists(bak), true); StringBuilder manifest = new StringBuilder(); CleanItem one = new CleanItem { Path = Path.Combine(root, "空1"), IsDir = true }; string moved = CleanOps.MoveToBackup(root, one, bak, manifest); Check("原位置已不存在", Directory.Exists(one.Path), false); Check("备份里有", Directory.Exists(moved), true); Check("manifest 有一行", manifest.ToString().Split('\n').Length >= 1, true); string mf = Path.Combine(bak, "manifest.txt"); File.WriteAllText(mf, manifest.ToString(), new UTF8Encoding(false)); string err0; int restored = CleanOps.Restore(mf, out err0); Check("还原 1 项", restored, 1); Check("还原到原位", Directory.Exists(one.Path), true); Check("还原无错误", err0, ""); // 直接删除空目录 Directory.CreateDirectory(Path.Combine(root, "待删")); CleanItem del = new CleanItem { Path = Path.Combine(root, "待删"), IsDir = true }; string e2; Check("删除空目录成功", CleanOps.DeleteNow(del, out e2), true); Check("删完就没了", Directory.Exists(del.Path), false); // 非空目录删不掉(保护) Directory.CreateDirectory(Path.Combine(root, "非空")); File.WriteAllText(Path.Combine(root, "非空", "a.txt"), "a"); CleanItem keep = new CleanItem { Path = Path.Combine(root, "非空"), IsDir = true }; string e3; Check("非空目录拒绝删除", CleanOps.DeleteNow(keep, out e3), false); Check("非空目录还在", Directory.Exists(keep.Path), true); Check("体积文本", CleanOps.SizeText(1536), "1.5 KB"); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 异常:" + ex.Message); } _lines.Add("通过 " + _pass + " / " + (_pass + _fail)); string all = string.Join("\r\n", _lines.ToArray()) + "\r\n"; Console.WriteLine(all); try { Directory.CreateDirectory(root); File.WriteAllText(Path.Combine(root, "selftest-emptyclean.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } static bool Has(List items, string path) { return IndexOf(items, path) >= 0; } static int IndexOf(List items, string path) { for (int i = 0; i < items.Count; i++) if (string.Equals(Path.GetFullPath(items[i].Path), Path.GetFullPath(path), StringComparison.OrdinalIgnoreCase)) return i; return -1; } static int CountFiles(List items) { int n = 0; foreach (CleanItem it in items) if (!it.IsDir) n++; return n; } } static class Program { [STAThread] static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(CleanSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new CleanForm()); } } }