// 文件夹大小分析 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法(net48 自带 csc 可编译) // 功能:递归扫描目录体积,最大文件/子文件夹排行,导出 txt 报告 // 边界:只读不写,扫描不改动任何文件;符号链接/junction 不跟随(防环) using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public class FolderSizeOps { public class Item { public string Path; // 完整路径 public string Name; // 显示名 public bool IsDir; public long Length; // 文件字节数 / 目录含子树字节数 public int Files; // 目录内文件数 } public class ScanResult { public List TopFiles = new List(); // 最大的文件 public List TopDirs = new List(); // 最占空间的直接子目录 public long TotalBytes; public int TotalFiles; public int TotalDirs; public int Errors; // 无权限等跳过的条数 public List ErrorList = new List(); } private static bool IsReparse(DirectoryInfo di) { // 防环: junction / symlink 目录不进入 return (di.Attributes & FileAttributes.ReparsePoint) != 0; } /* 递归统计。dirAgg: 目录完整路径 → 该目录子树总字节(含自身下所有文件) */ public static ScanResult Scan(string root) { ScanResult r = new ScanResult(); if (!Directory.Exists(root)) throw new IOException("目录不存在:" + root); Dictionary dirAgg = new Dictionary(); Walk(new DirectoryInfo(root), r, dirAgg); r.TotalBytes = AggGet(dirAgg, Path.GetFullPath(root).TrimEnd('\\')); // 直接子目录排行(用聚合值) List subs = new List(); DirectoryInfo rootDi = new DirectoryInfo(root); try { DirectoryInfo[] subs_ = rootDi.GetDirectories(); foreach (DirectoryInfo sd in subs_) { if (IsReparse(sd)) continue; Item it = new Item(); it.Path = sd.FullName; it.Name = sd.Name; it.IsDir = true; it.Length = AggGet(dirAgg, sd.FullName); it.Files = -1; // 子目录文件数不再逐个给,避免二次扫描 subs.Add(it); } } catch { } subs.Sort(delegate(Item a, Item b) { return b.Length.CompareTo(a.Length); }); for (int i = 0; i < subs.Count && i < 50; i++) r.TopDirs.Add(subs[i]); // 文件排行 List files = FileBag.Files; files.Sort(delegate(Item a, Item b) { return b.Length.CompareTo(a.Length); }); for (int i = 0; i < files.Count && i < 200; i++) r.TopFiles.Add(files[i]); return r; } private static long AggGet(Dictionary agg, string p) { long v; return agg.TryGetValue(p, out v) ? v : 0; } // 文件收集容器(扫描中间结果,避免在 Item 里回填) internal static class FileBag { public static List Files = new List(); } private static long Walk(DirectoryInfo di, ScanResult r, Dictionary dirAgg) { long sum = 0; r.TotalDirs++; try { FileInfo[] fs = di.GetFiles(); foreach (FileInfo f in fs) { long len; try { len = f.Length; } catch { r.Errors++; r.ErrorList.Add("读不到:" + f.FullName); continue; } sum += len; r.TotalFiles++; Item it = new Item(); it.Path = f.FullName; it.Name = f.Name; it.IsDir = false; it.Length = len; FileBag.Files.Add(it); } DirectoryInfo[] ds = di.GetDirectories(); foreach (DirectoryInfo sd in ds) { if (IsReparse(sd)) { r.Errors++; r.ErrorList.Add("跳过符号链接:" + sd.FullName); continue; } sum += Walk(sd, r, dirAgg); } } catch (Exception ex) { r.Errors++; r.ErrorList.Add("进不去:" + di.FullName + "(" + ex.GetType().Name + ")"); } dirAgg[di.FullName] = sum; // 本目录直接文件之和;子目录聚合在下面补 return sum; } /* 聚合说明:Walk 返回值 = 该目录子树总字节,末尾存进 dirAgg, 所以 TopDirs 直接查表就是「含子树」的大小,不需要二次计算 */ 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 static string BuildReport(string root, ScanResult r) { StringBuilder sb = new StringBuilder(); sb.AppendLine("文件夹大小分析报告"); sb.AppendLine("目录:" + root); sb.AppendLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); sb.AppendLine("总计:" + FormatSize(r.TotalBytes) + "," + r.TotalFiles + " 个文件," + r.TotalDirs + " 个目录" + (r.Errors > 0 ? "(" + r.Errors + " 项跳过)" : "")); sb.AppendLine(); sb.AppendLine("== 最占空间的子目录(直接子目录,含子树)=="); foreach (Item it in r.TopDirs) sb.AppendLine(FormatSize(it.Length).PadLeft(12) + " " + it.Name); sb.AppendLine(); sb.AppendLine("== 最大的文件 TOP " + r.TopFiles.Count + " =="); foreach (Item it in r.TopFiles) sb.AppendLine(FormatSize(it.Length).PadLeft(12) + " " + it.Path); if (r.ErrorList.Count > 0) { sb.AppendLine(); sb.AppendLine("== 跳过的条目 =="); foreach (string e in r.ErrorList) sb.AppendLine(e); } return sb.ToString(); } } public class FolderSizeForm : Form { private TextBox txtDir; private Button btnPick; private Button btnScan; private Button btnExport; private ListView lv; private ColumnHeader colSize; private ColumnHeader colName; private Label lblStatus; private ProgressBar progress; private BackgroundWorker worker; private FolderSizeOps.ScanResult last; private string lastRoot = ""; public FolderSizeForm() { InitUi(); worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.DoWork += new DoWorkEventHandler(WorkerDoWork); worker.ProgressChanged += new ProgressChangedEventHandler(WorkerProgress); 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); txtDir.TextChanged += new EventHandler(AnyInput); 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); btnExport = new Button(); btnExport.Text = "导出报告 (txt)"; btnExport.Location = new Point(x + 156, y); btnExport.Size = new Size(140, 34); btnExport.Enabled = false; btnExport.Click += new EventHandler(ExportClick); this.Controls.Add(btnExport); progress = new ProgressBar(); progress.Location = new Point(320, y + 6); progress.Size = new Size(440, 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("排名", 52); colSize = lv.Columns.Add("大小", 100, HorizontalAlignment.Right); colName = lv.Columns.Add("文件 / 子目录(点击列头切换两类)", 560); lv.ColumnClick += new ColumnClickEventHandler(LvClick); lv.DoubleClick += new EventHandler(LvOpen); this.Controls.Add(lv); } private bool showDirs = true; private void LvClick(object sender, ColumnClickEventArgs e) { if (last != null) FillList(e.Column != 2); // 点"名称"列显示目录,点"大小"列显示文件 } private void FillList(bool dirs) { showDirs = dirs; lv.BeginUpdate(); lv.Items.Clear(); List list = dirs ? (List)last.TopDirs : last.TopFiles; for (int i = 0; i < list.Count; i++) { FolderSizeOps.Item it = list[i]; ListViewItem li = new ListViewItem((i + 1).ToString()); li.SubItems.Add(FolderSizeOps.FormatSize(it.Length)); li.SubItems.Add(it.IsDir ? "[目录] " + it.Name : it.Name); li.Tag = it; if (i < 3) li.ForeColor = Color.FromArgb(0, 145, 88); lv.Items.Add(li); } lv.EndUpdate(); colName.Text = dirs ? "子目录(含子树,点击「大小」列看文件排行)" : "文件(点击「名称」列回目录排行)"; } private void LvOpen(object sender, EventArgs e) { if (lv.SelectedItems.Count == 0) return; FolderSizeOps.Item it = lv.SelectedItems[0].Tag as FolderSizeOps.Item; if (it != null && it.IsDir) { txtDir.Text = it.Path; ScanClick(null, EventArgs.Empty); } } 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 AnyInput(object sender, EventArgs e) { } 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; } FolderSizeOps.FileBag.Files = new List(); btnScan.Enabled = false; btnExport.Enabled = false; progress.Visible = true; worker.RunWorkerAsync(dir); } private void WorkerDoWork(object sender, DoWorkEventArgs e) { string dir = (string)e.Argument; e.Result = FolderSizeOps.Scan(dir); } private void WorkerProgress(object sender, ProgressChangedEventArgs e) { } 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 = (FolderSizeOps.ScanResult)e.Result; lastRoot = txtDir.Text.Trim(); FillList(true); lblStatus.ForeColor = Color.FromArgb(0, 145, 88); lblStatus.Text = "共 " + FolderSizeOps.FormatSize(last.TotalBytes) + "|" + last.TotalFiles + " 个文件|" + last.TotalDirs + " 个目录" + (last.Errors > 0 ? "|跳过 " + last.Errors + " 项(见报告)" : ""); btnExport.Enabled = true; } 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; File.WriteAllText(dlg.FileName, FolderSizeOps.BuildReport(lastRoot, last), new UTF8Encoding(true)); lblStatus.Text = "报告已保存:" + dlg.FileName; } } // ───────────────────────── 自测 ───────────────────────── public static class FolderSizeSelfTest { 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-foldersize-" + Guid.NewGuid().ToString("N").Substring(0, 8)) : dir; try { Directory.CreateDirectory(baseDir); // 结构: // a.txt 1000 B // big.bin 5 MB // sub1\ (2 个文件:2000 B + 3000 B) + sub1\deep\deep.bin 1 MB // sub2\ (1 个文件 500 B) // empty\ (空目录) File.WriteAllBytes(Path.Combine(baseDir, "a.txt"), new byte[1000]); File.WriteAllBytes(Path.Combine(baseDir, "big.bin"), new byte[5 * 1024 * 1024]); string s1 = Path.Combine(baseDir, "sub1"); string deep = Path.Combine(s1, "deep"); Directory.CreateDirectory(deep); Directory.CreateDirectory(Path.Combine(baseDir, "sub2")); Directory.CreateDirectory(Path.Combine(baseDir, "empty")); File.WriteAllBytes(Path.Combine(s1, "x1.dat"), new byte[2000]); File.WriteAllBytes(Path.Combine(s1, "x2.dat"), new byte[3000]); File.WriteAllBytes(Path.Combine(deep, "deep.bin"), new byte[1024 * 1024]); File.WriteAllBytes(Path.Combine(baseDir, "sub2", "y.txt"), new byte[500]); FolderSizeOps.FileBag.Files = new List(); FolderSizeOps.ScanResult r = FolderSizeOps.Scan(baseDir); long want = 1000L + 5 * 1024 * 1024 + 2000 + 3000 + 1024 * 1024 + 500; Check("总字节数", r.TotalBytes, want); Check("文件总数", r.TotalFiles, 6); Check("目录数(含空目录,不含根)", r.TotalDirs, 5); Check("无错误", r.Errors, 0); Check("最大文件是 big.bin", r.TopFiles[0].Name + "|" + r.TopFiles[0].Length, "big.bin|" + (5 * 1024 * 1024)); Check("文件排行含深层文件", r.TopFiles.FindIndex(delegate(FolderSizeOps.Item i) { return i.Name == "deep.bin"; }) >= 0, true); // 子目录聚合:sub1 = 2000+3000+1MB(含 deep),sub2 = 500,empty = 0 FolderSizeOps.Item s1i = r.TopDirs.Find(delegate(FolderSizeOps.Item i) { return i.Name == "sub1"; }); Check("sub1 聚合含深层", s1i.Length, 2000L + 3000 + 1024 * 1024); FolderSizeOps.Item s2i = r.TopDirs.Find(delegate(FolderSizeOps.Item i) { return i.Name == "sub2"; }); Check("sub2 聚合", s2i.Length, 500L); FolderSizeOps.Item ei = r.TopDirs.Find(delegate(FolderSizeOps.Item i) { return i.Name == "empty"; }); Check("空目录聚合为 0", ei.Length, 0L); Check("目录排行按大小降序", r.TopDirs[0].Name, "sub1"); // 报告导出 string report = FolderSizeOps.BuildReport(baseDir, r); Check("报告含总计", report.Contains(FolderSizeOps.FormatSize(want)), true); Check("报告含深层文件路径", report.Contains("deep.bin"), true); Check("报告含子目录排行", report.IndexOf("sub1") < report.IndexOf("sub2"), true); // 体积格式化 Check("0 B", FolderSizeOps.FormatSize(0), "0 B"); Check("1 KB", FolderSizeOps.FormatSize(1024), "1 KB"); Check("1.5 MB", FolderSizeOps.FormatSize(1536 * 1024), "1.5 MB"); // 不存在的目录要报错 bool threw = false; try { FolderSizeOps.Scan(Path.Combine(baseDir, "no-such-dir")); } 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-foldersize.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(FolderSizeSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FolderSizeForm()); } } }