// 文件夹清单导出 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法(net48 自带 csc 可编译) // 功能:把一个文件夹的目录树/明细清单导成 txt、CSV(Excel 直接开)、Markdown 报告 // 边界:只读,不移动不删除任何文件;没有权限的目录跳过并在结果里注明 // 原理:一次遍历建树,各格式共用同一份统计,避免三种格式数字对不上 using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public class DirListOps { public class Node { public string Name; public string FullPath; public bool IsDir; public long Size; public DateTime Modified; public long FileCount; public long TotalSize; public List Children = new List(); } public class Options { public bool Recursive = true; public bool IncludeHidden = false; public bool IncludeSizes = true; public string ExtFilter = ""; // 空 = 全部;否则 ".jpg,.png" public int MaxDepth = 0; // 0 = 不限 } public class Stats { public long Files; public long Dirs; public long TotalSize; public long Skipped; public string BiggestFile = ""; public long BiggestSize; public DateTime Newest = DateTime.MinValue; public Node Root; } /* 扩展名过滤:空表表示全部;比较时不区分大小写 */ public static bool ExtOk(string name, string filter) { if (string.IsNullOrEmpty(filter)) return true; string e = Path.GetExtension(name).ToLowerInvariant(); string[] parts = filter.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string p in parts) { string q = p.Trim().ToLowerInvariant(); if (q.Length == 0) continue; if (q.StartsWith(".") ? q == e : ("." + q) == e) return true; } return false; } public static bool HasExtFilter(string filter) { return !string.IsNullOrEmpty(filter) && filter.Trim(new char[] { ',', ';', ' ' }).Length > 0; } static bool Hidden(string path, string name) { if (name.StartsWith(".")) return true; try { FileAttributes a = File.GetAttributes(path); return (a & FileAttributes.Hidden) != 0; } catch { return false; } } public static Stats Scan(string root, Options opt) { if (!Directory.Exists(root)) throw new IOException("目录不存在:" + root); Stats st = new Stats(); st.Root = Walk(root, root, 1, opt, st); return st; } static Node Walk(string root, string dir, int depth, Options opt, Stats st) { Node node = new Node(); node.Name = Path.GetFileName(dir.TrimEnd('\\')); if (node.Name.Length == 0) node.Name = dir; // 根盘符 C:\ node.FullPath = dir; node.IsDir = true; node.Modified = SafeTime(dir); // 目录自身先入表:文件夹数包含自己下的子目录 try { foreach (string d in Directory.GetDirectories(dir)) { string dn = Path.GetFileName(d); if (!opt.IncludeHidden && Hidden(d, dn)) { st.Skipped++; continue; } if (opt.MaxDepth > 0 && depth >= opt.MaxDepth) { st.Skipped++; continue; } if (opt.Recursive) { node.Children.Add(Walk(root, d, depth + 1, opt, st)); } else { st.Skipped++; // 不递归时子目录不展开 } } } catch { st.Skipped++; } try { foreach (string f in Directory.GetFiles(dir)) { string fn = Path.GetFileName(f); if (!opt.IncludeHidden && Hidden(f, fn)) { st.Skipped++; continue; } if (HasExtFilter(opt.ExtFilter) && !ExtOk(fn, opt.ExtFilter)) continue; Node child = new Node(); child.Name = fn; child.FullPath = f; child.IsDir = false; try { FileInfo fi = new FileInfo(f); child.Size = fi.Length; child.Modified = fi.LastWriteTime; } catch { child.Size = 0; child.Modified = DateTime.MinValue; } node.Children.Add(child); st.Files++; st.TotalSize += child.Size; if (child.Size > st.BiggestSize) { st.BiggestSize = child.Size; st.BiggestFile = f; } if (child.Modified > st.Newest) st.Newest = child.Modified; } } catch { st.Skipped++; } node.Children.Sort(delegate(Node a, Node b) { if (a.IsDir != b.IsDir) return a.IsDir ? -1 : 1; return string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase); }); foreach (Node c in node.Children) { if (c.IsDir) { node.FileCount += c.FileCount; node.TotalSize += c.TotalSize; st.Dirs++; } else { node.FileCount++; node.TotalSize += c.Size; } } return node; } static DateTime SafeTime(string path) { try { return Directory.GetLastWriteTime(path); } catch { return DateTime.MinValue; } } public static string SizeText(long n) { if (n < 1024) return n + " B"; if (n < 1024 * 1024) return (n / 1024.0).ToString("0.0") + " KB"; if (n < 1024L * 1024 * 1024) return (n / 1048576.0).ToString("0.0") + " MB"; return (n / 1073741824.0).ToString("0.00") + " GB"; } public static string RelPath(string root, string full) { string r = root.TrimEnd('\\'); if (full.Length <= r.Length) return Path.GetFileName(full); return full.Substring(r.Length).TrimStart('\\'); } // ───────────── 目录树(txt)───────────── public static string TreeText(Stats st, Options opt) { StringBuilder sb = new StringBuilder(); sb.AppendLine(st.Root.Name + "\\"); if (opt.IncludeSizes) sb.AppendLine("(共 " + st.Files + " 个文件," + st.Dirs + " 个文件夹," + SizeText(st.TotalSize) + ")"); sb.AppendLine(); RenderTree(st.Root, "", sb, opt, 1); return sb.ToString(); } static void RenderTree(Node n, string prefix, StringBuilder sb, Options opt, int depth) { for (int i = 0; i < n.Children.Count; i++) { Node c = n.Children[i]; bool last = (i == n.Children.Count - 1); sb.Append(prefix); sb.Append(last ? "└── " : "├── "); sb.Append(c.Name); if (c.IsDir) { sb.Append("\\"); if (opt.IncludeSizes) sb.Append(" (" + c.FileCount + " 个文件, " + SizeText(c.TotalSize) + ")"); } else if (opt.IncludeSizes) { sb.Append(" " + SizeText(c.Size)); } sb.AppendLine(); if (c.IsDir && (opt.MaxDepth == 0 || depth < opt.MaxDepth)) RenderTree(c, prefix + (last ? " " : "│ "), sb, opt, depth + 1); } } // ───────────── 明细(CSV,UTF-8 BOM 让 Excel 不乱码)───────────── public static string CsvText(Stats st, Options opt) { StringBuilder sb = new StringBuilder(); sb.AppendLine("相对路径,名称,类型,大小(字节),大小,修改时间,扩展名"); AppendCsvRows(st.Root, st, sb, opt); return sb.ToString(); } static void AppendCsvRows(Node n, Stats st, StringBuilder sb, Options opt) { foreach (Node c in n.Children) { sb.Append(CsvCell(RelPath(st.Root.FullPath, c.FullPath))); sb.Append(",").Append(CsvCell(c.Name)); sb.Append(",").Append(c.IsDir ? "文件夹" : "文件"); sb.Append(",").Append(c.IsDir ? "" : c.Size.ToString()); sb.Append(",").Append(c.IsDir ? SizeText(c.TotalSize) : SizeText(c.Size)); sb.Append(",").Append(c.Modified == DateTime.MinValue ? "" : c.Modified.ToString("yyyy-MM-dd HH:mm:ss")); sb.Append(",").Append(c.IsDir ? "" : Path.GetExtension(c.Name).ToLowerInvariant()); sb.AppendLine(); if (c.IsDir) AppendCsvRows(c, st, sb, opt); } } public static string CsvCell(string s) { if (s == null) return ""; bool need = s.IndexOf(',') >= 0 || s.IndexOf('"') >= 0 || s.IndexOf('\n') >= 0 || s.IndexOf('\r') >= 0; if (!need) return s; return "\"" + s.Replace("\"", "\"\"") + "\""; } // ───────────── 报告(Markdown)───────────── public static string MdText(Stats st, Options opt) { StringBuilder sb = new StringBuilder(); string rootName = st.Root.Name; sb.AppendLine("# 文件夹清单:" + rootName); sb.AppendLine(); sb.AppendLine("生成时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " "); sb.AppendLine("扫描路径:`" + st.Root.FullPath + "`"); sb.AppendLine(); sb.AppendLine("## 概览"); sb.AppendLine(); sb.AppendLine("| 项目 | 数值 |"); sb.AppendLine("| --- | --- |"); sb.AppendLine("| 文件数 | " + st.Files + " |"); sb.AppendLine("| 文件夹数 | " + st.Dirs + " |"); sb.AppendLine("| 总体积 | " + SizeText(st.TotalSize) + "(" + st.TotalSize + " 字节) |"); sb.AppendLine("| 最大的文件 | " + (st.BiggestFile.Length == 0 ? "—" : "`" + RelPath(st.Root.FullPath, st.BiggestFile) + "`(" + SizeText(st.BiggestSize) + ")") + " |"); sb.AppendLine("| 最近修改 | " + (st.Newest == DateTime.MinValue ? "—" : st.Newest.ToString("yyyy-MM-dd HH:mm")) + " |"); if (st.Skipped > 0) sb.AppendLine("| 跳过 | " + st.Skipped + " 项(隐藏项或无权限,未计入) |"); sb.AppendLine(); List> ext = ExtStats(st); if (ext.Count > 0) { sb.AppendLine("## 按扩展名统计"); sb.AppendLine(); sb.AppendLine("| 扩展名 | 数量 | 体积 |"); sb.AppendLine("| --- | --- | --- |"); int shown = 0; foreach (KeyValuePair kv in ext) { sb.AppendLine("| " + (kv.Key.Length == 0 ? "(无扩展名)" : kv.Key) + " | " + kv.Value + " | — |"); shown++; if (shown >= 12) break; } sb.AppendLine(); } List big = TopFiles(st.Root, 15); if (big.Count > 0) { sb.AppendLine("## 最大的 15 个文件"); sb.AppendLine(); sb.AppendLine("| 文件 | 大小 |"); sb.AppendLine("| --- | --- |"); foreach (Node n in big) sb.AppendLine("| `" + RelPath(st.Root.FullPath, n.FullPath) + "` | " + SizeText(n.Size) + " |"); sb.AppendLine(); } sb.AppendLine("## 目录树"); sb.AppendLine(); sb.AppendLine("```"); sb.Append(TreeText(st, opt)); sb.AppendLine("```"); return sb.ToString(); } /* 扩展名 → 文件数,按数量倒序 */ public static List> ExtStats(Stats st) { Dictionary d = new Dictionary(); CollectExt(st.Root, d); List> list = new List>(d); list.Sort(delegate(KeyValuePair a, KeyValuePair b) { if (a.Value != b.Value) return b.Value.CompareTo(a.Value); return string.Compare(a.Key, b.Key, StringComparison.OrdinalIgnoreCase); }); return list; } static void CollectExt(Node n, Dictionary d) { foreach (Node c in n.Children) { if (c.IsDir) { CollectExt(c, d); continue; } string e = Path.GetExtension(c.Name).ToLowerInvariant(); if (!d.ContainsKey(e)) d[e] = 0; d[e] = d[e] + 1; } } public static List TopFiles(Node root, int n) { List all = new List(); CollectFiles(root, all); all.Sort(delegate(Node a, Node b) { return b.Size.CompareTo(a.Size); }); if (all.Count > n) all.RemoveRange(n, all.Count - n); return all; } static void CollectFiles(Node n, List all) { foreach (Node c in n.Children) { if (c.IsDir) CollectFiles(c, all); else all.Add(c); } } public static void Save(string path, string content, bool bom) { File.WriteAllText(path, content, new UTF8Encoding(bom)); } } public class DirListForm : Form { private TextBox txtDir; private Button btnPick; private TextBox txtExt; private CheckBox chkRecursive; private CheckBox chkHidden; private CheckBox chkSizes; private ComboBox cbFormat; private Button btnExport; private Button btnCopy; private Button btnPreview; private TextBox txtPreview; private Label lblStatus; public DirListForm() { InitUi(); } 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(820, 560); this.MinimumSize = new Size(720, 500); this.AllowDrop = true; this.DragEnter += new DragEventHandler(FormDragEnter); this.DragDrop += new DragEventHandler(FormDragDrop); int x = 20, y = 16; Label lblTitle = new Label(); lblTitle.Text = "导出目录树和文件明细:txt 看结构、CSV 进 Excel、Markdown 交报告,只读不删改"; 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(620, 26); this.Controls.Add(txtDir); btnPick = new Button(); btnPick.Text = "浏览…"; btnPick.Location = new Point(652, y - 1); btnPick.Size = new Size(90, 28); btnPick.Click += new EventHandler(PickClick); this.Controls.Add(btnPick); y += 40; Label lbExt = new Label(); lbExt.Text = "只要这些扩展名"; lbExt.Location = new Point(x, y + 2); lbExt.AutoSize = true; this.Controls.Add(lbExt); txtExt = new TextBox(); txtExt.Location = new Point(x + 112, y); txtExt.Size = new Size(180, 26); txtExt.Text = ""; this.Controls.Add(txtExt); Label lbHint = new Label(); lbHint.Text = "留空=全部,例:.jpg,.png"; lbHint.Location = new Point(x + 300, y + 3); lbHint.AutoSize = true; lbHint.ForeColor = Color.FromArgb(120, 130, 124); this.Controls.Add(lbHint); y += 38; chkRecursive = new CheckBox(); chkRecursive.Text = "含子文件夹"; chkRecursive.Location = new Point(x, y); chkRecursive.AutoSize = true; chkRecursive.Checked = true; this.Controls.Add(chkRecursive); chkHidden = new CheckBox(); chkHidden.Text = "含隐藏文件"; chkHidden.Location = new Point(x + 118, y); chkHidden.AutoSize = true; this.Controls.Add(chkHidden); chkSizes = new CheckBox(); chkSizes.Text = "显示大小"; chkSizes.Location = new Point(x + 226, y); chkSizes.AutoSize = true; chkSizes.Checked = true; this.Controls.Add(chkSizes); y += 38; Label lbFmt = new Label(); lbFmt.Text = "导出格式"; lbFmt.Location = new Point(x, y + 3); lbFmt.AutoSize = true; this.Controls.Add(lbFmt); cbFormat = new ComboBox(); cbFormat.DropDownStyle = ComboBoxStyle.DropDownList; cbFormat.Location = new Point(x + 74, y); cbFormat.Size = new Size(240, 26); cbFormat.Items.Add("目录树 .txt(看结构最直观)"); cbFormat.Items.Add("明细 .csv(Excel 直接打开)"); cbFormat.Items.Add("报告 .md(概览 + 排行 + 树)"); cbFormat.SelectedIndex = 0; this.Controls.Add(cbFormat); y += 44; btnPreview = new Button(); btnPreview.Text = "预览"; btnPreview.Location = new Point(x, y); btnPreview.Size = new Size(100, 34); btnPreview.Click += new EventHandler(PreviewClick); this.Controls.Add(btnPreview); btnExport = new Button(); btnExport.Text = "导出文件…"; btnExport.Location = new Point(x + 112, y); btnExport.Size = new Size(130, 34); btnExport.BackColor = Color.FromArgb(0, 145, 88); btnExport.ForeColor = Color.White; btnExport.FlatStyle = FlatStyle.Flat; btnExport.Click += new EventHandler(ExportClick); this.Controls.Add(btnExport); btnCopy = new Button(); btnCopy.Text = "复制到剪贴板"; btnCopy.Location = new Point(x + 254, y); btnCopy.Size = new Size(130, 34); btnCopy.Click += new EventHandler(CopyClick); this.Controls.Add(btnCopy); y += 48; 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 += 26; txtPreview = new TextBox(); txtPreview.Multiline = true; txtPreview.ScrollBars = ScrollBars.Both; txtPreview.WordWrap = false; txtPreview.ReadOnly = true; txtPreview.Font = new Font("Consolas", 9.5f); txtPreview.Location = new Point(x, y); txtPreview.Size = new Size(780, 320); txtPreview.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; this.Controls.Add(txtPreview); } 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 DirListOps.Options Options() { DirListOps.Options o = new DirListOps.Options(); o.Recursive = chkRecursive.Checked; o.IncludeHidden = chkHidden.Checked; o.IncludeSizes = chkSizes.Checked; o.ExtFilter = (txtExt.Text ?? "").Trim(); return o; } private string Build(string dir, DirListOps.Options o, DirListOps.Stats st) { int idx = cbFormat.SelectedIndex; if (idx == 1) return DirListOps.CsvText(st, o); if (idx == 2) return DirListOps.MdText(st, o); return DirListOps.TreeText(st, o); } private void PreviewClick(object sender, EventArgs e) { string dir = (txtDir.Text ?? "").Trim(); if (dir.Length == 0 || !Directory.Exists(dir)) { lblStatus.ForeColor = Color.FromArgb(200, 50, 50); lblStatus.Text = "先选一个存在的文件夹。"; return; } try { DirListOps.Options o = Options(); DirListOps.Stats st = DirListOps.Scan(dir, o); string text = Build(dir, o, st); if (text.Length > 200000) text = text.Substring(0, 200000) + "\r\n……(太长,预览截断,导出仍是完整内容)"; txtPreview.Text = text.Replace("\n", "\r\n").Replace("\r\r\n", "\r\n"); lblStatus.ForeColor = Color.FromArgb(0, 145, 88); lblStatus.Text = st.Files + " 个文件 / " + st.Dirs + " 个文件夹 / 共 " + DirListOps.SizeText(st.TotalSize) + (st.Skipped > 0 ? ";跳过 " + st.Skipped + " 项" : ""); } catch (Exception ex) { lblStatus.ForeColor = Color.FromArgb(200, 50, 50); lblStatus.Text = "扫描失败:" + ex.Message; } } private void ExportClick(object sender, EventArgs e) { string dir = (txtDir.Text ?? "").Trim(); if (dir.Length == 0 || !Directory.Exists(dir)) { lblStatus.ForeColor = Color.FromArgb(200, 50, 50); lblStatus.Text = "先选一个存在的文件夹。"; return; } try { DirListOps.Options o = Options(); DirListOps.Stats st = DirListOps.Scan(dir, o); string text = Build(dir, o, st); int idx = cbFormat.SelectedIndex; string ext = idx == 1 ? ".csv" : idx == 2 ? ".md" : ".txt"; SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = idx == 1 ? "CSV 表格|*.csv" : idx == 2 ? "Markdown|*.md" : "文本文件|*.txt"; string baseName = Path.GetFileName(dir.TrimEnd('\\')); if (baseName.Length == 0) baseName = "清单"; dlg.FileName = baseName + "-清单" + ext; if (dlg.ShowDialog(this) != DialogResult.OK) return; DirListOps.Save(dlg.FileName, text, idx == 1); // CSV 加 BOM,Excel 才不乱码 lblStatus.ForeColor = Color.FromArgb(0, 145, 88); lblStatus.Text = "已导出 " + st.Files + " 个文件 / " + st.Dirs + " 个文件夹 → " + dlg.FileName; txtPreview.Text = text.Replace("\n", "\r\n").Replace("\r\r\n", "\r\n"); } catch (Exception ex) { lblStatus.ForeColor = Color.FromArgb(200, 50, 50); lblStatus.Text = "导出失败:" + ex.Message; } } private void CopyClick(object sender, EventArgs e) { if (txtPreview.Text.Length == 0) { PreviewClick(sender, e); } if (txtPreview.Text.Length == 0) return; try { Clipboard.SetText(txtPreview.Text); lblStatus.ForeColor = Color.FromArgb(0, 145, 88); lblStatus.Text = "已复制到剪贴板。"; } catch (Exception ex) { lblStatus.ForeColor = Color.FromArgb(200, 50, 50); lblStatus.Text = "复制失败:" + ex.Message; } } } // ───────────────────────── 自测 ───────────────────────── public static class DirListSelfTest { 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); } } static bool Has(string text, string part) { return text.IndexOf(part, StringComparison.Ordinal) >= 0; } 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-dirlist-" + Guid.NewGuid().ToString("N").Substring(0, 8)) : dir; try { Directory.CreateDirectory(baseDir); // 造树:根 10B + 2048B + 子目录 100B + 深层 5B File.WriteAllText(Path.Combine(baseDir, "a.txt"), "0123456789", new UTF8Encoding(false)); File.WriteAllBytes(Path.Combine(baseDir, "b.jpg"), new byte[2048]); string sub = Path.Combine(baseDir, "sub"); Directory.CreateDirectory(sub); File.WriteAllText(Path.Combine(sub, "c.txt"), new string('x', 100), new UTF8Encoding(false)); string deep = Path.Combine(sub, "deep"); Directory.CreateDirectory(deep); File.WriteAllText(Path.Combine(deep, "d.md"), "hello", new UTF8Encoding(false)); File.WriteAllText(Path.Combine(baseDir, "带,逗号 和空格.csv"), "x", new UTF8Encoding(false)); string hid = Path.Combine(baseDir, "hidden.dat"); File.WriteAllText(hid, "h", new UTF8Encoding(false)); File.SetAttributes(hid, FileAttributes.Hidden); DirListOps.Options opt = new DirListOps.Options(); DirListOps.Stats st = DirListOps.Scan(baseDir, opt); Check("文件数(隐藏不算)", st.Files, 5); Check("文件夹数(sub+deep)", st.Dirs, 2); Check("总体积", st.TotalSize, 10 + 2048 + 100 + 5 + 1); Check("最大文件是 b.jpg", Path.GetFileName(st.BiggestFile), "b.jpg"); Check("根目录树大小聚合", st.Root.TotalSize, 10 + 2048 + 100 + 5 + 1); Check("根文件计数聚合", st.Root.FileCount, 5); string tree = DirListOps.TreeText(st, opt); Check("树含根名", Has(tree, Path.GetFileName(baseDir)), true); Check("树用 ├──", Has(tree, "├── "), true); Check("树用 └──", Has(tree, "└── "), true); Check("树含深层文件", Has(tree, "d.md"), true); Check("树含大小", Has(tree, "2.0 KB"), true); Check("树首行是根", tree.StartsWith(Path.GetFileName(baseDir) + "\\"), true); string csv = DirListOps.CsvText(st, opt); Check("CSV 表头", csv.StartsWith("相对路径,名称,类型,大小(字节),大小,修改时间,扩展名"), true); Check("CSV 行数(表头+7)", csv.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).Length, 8); Check("CSV 逗号名加引号", Has(csv, "\"带,逗号 和空格.csv\""), true); Check("CSV 引号转义(直接测函数)", DirListOps.CsvCell("a\"b"), "\"a\"\"b\""); Check("CSV 相对路径含子目录", Has(csv, "sub\\c.txt"), true); Check("CSV 文件夹大小填写", Has(csv, "文件夹"), true); string md = DirListOps.MdText(st, opt); Check("MD 有概览", Has(md, "## 概览"), true); Check("MD 有文件数", Has(md, "| 文件数 | 5 |"), true); Check("MD 有扩展名统计", Has(md, "## 按扩展名统计"), true); Check("MD 有最大文件榜", Has(md, "## 最大的 15 个文件"), true); Check("MD 有目录树块", Has(md, "## 目录树"), true); Check("MD 概览体积", Has(md, DirListOps.SizeText(10 + 2048 + 100 + 5 + 1)), true); // 扩展名过滤 DirListOps.Options onlyJpg = new DirListOps.Options(); onlyJpg.ExtFilter = ".jpg"; DirListOps.Stats st2 = DirListOps.Scan(baseDir, onlyJpg); Check("扩展名过滤只剩 1 个", st2.Files, 1); Check("过滤后体积", st2.TotalSize, 2048); // 不带点也认 DirListOps.Options noDot = new DirListOps.Options(); noDot.ExtFilter = "jpg,png"; Check("扩展名不带点也认", DirListOps.Scan(baseDir, noDot).Files, 1); // 隐藏文件 DirListOps.Options withHidden = new DirListOps.Options(); withHidden.IncludeHidden = true; Check("含隐藏后 6 个", DirListOps.Scan(baseDir, withHidden).Files, 6); // 不递归 DirListOps.Options flat = new DirListOps.Options(); flat.Recursive = false; DirListOps.Stats st3 = DirListOps.Scan(baseDir, flat); Check("不递归只数根文件", st3.Files, 3); Check("不递归不算子目录文件数", st3.Root.FileCount, 3); Check("不递归跳过子目录", st3.Skipped >= 1, true); // 空目录 string emptyDir = Path.Combine(baseDir, "empty"); Directory.CreateDirectory(emptyDir); DirListOps.Stats st4 = DirListOps.Scan(emptyDir, new DirListOps.Options()); Check("空目录 0 文件", st4.Files, 0); Check("空目录树只有根行", DirListOps.TreeText(st4, opt).Trim().Length > 0, true); // 保存编码 string outCsv = Path.Combine(baseDir, "out.csv"); DirListOps.Save(outCsv, csv, true); byte[] b = File.ReadAllBytes(outCsv); Check("CSV 有 BOM", b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF, true); string outTxt = Path.Combine(baseDir, "out.txt"); DirListOps.Save(outTxt, tree, false); Check("txt 无 BOM", File.ReadAllBytes(outTxt)[0] != 0xEF, true); Check("txt 内容可读回", File.ReadAllText(outTxt, new UTF8Encoding(false)) == tree, true); bool threw = false; try { DirListOps.Scan(Path.Combine(baseDir, "nope"), opt); } catch { threw = true; } Check("目录不存在抛异常", threw ? "threw" : "silent", "threw"); // 只读性:扫完源文件还在、大小没变 Check("源文件没被删", File.Exists(Path.Combine(baseDir, "a.txt")), true); Check("源文件大小没变", new FileInfo(Path.Combine(baseDir, "b.jpg")).Length, 2048); } 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-dirlist.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(DirListSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new DirListForm()); } } }