commit aaf36959d1567e6ec763b20b4bd0991e8584acd3 Author: Zhang Pu <1651@88.com> Date: Mon Nov 2 11:12:18 2026 +0800 init: zpclean v1.0.0 首次发布 - 加固版留言系统 / 磁盘清理助手 - MIT License diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4fc8afb --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +bin/ +obj/ +publish/ +*.user +.vs/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5519491 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Zhang Pu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/MainForm.cs b/MainForm.cs new file mode 100644 index 0000000..424e61d --- /dev/null +++ b/MainForm.cs @@ -0,0 +1,685 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Windows.Forms; +using Microsoft.VisualBasic.FileIO; + +namespace ZPclean +{ + /// + /// ZPclean - 磁盘清理助手(重写版 2026-10-30) + /// 相比初版修复: + /// 1. 中文乱码(所有文案 UTF-8) + /// 2. 大文件/重复文件扫描遇到无权限目录直接抛异常中断 → 改为安全递归(逐目录 try/catch + 跳过链接目录) + /// 3. 进度条不更新 → 改为实时进度 + 可取消 + /// 4. 大文件/重复文件状态显示串到「C盘垃圾」标签 → 各页归位 + /// 5. 只扫描不清理 → 增加「移到回收站 / 永久删除」两种清理方式(二次确认) + /// 6. 重复文件直接全盘算 MD5(极慢)→ 改为先按大小分组,再只对同大小组算哈希 + /// 7. 微信目录只认老路径 → 兼容 WeChat Files / xwechat_files / AppData\Tencent\WeChat + /// + public class MainForm : Form + { + // ---------- 通用状态 ---------- + private volatile bool _cancel = false; + private readonly List _junkItems = new List(); + private readonly List _wechatItems = new List(); + private readonly List _bigItems = new List(); + private readonly List _dupItems = new List(); + + // ---------- Tab1 垃圾 ---------- + private ListView lvJunk = new ListView(); + private Label lblJunkStatus = new Label(); + private ProgressBar pbJunk = new ProgressBar(); + private Button btnScanJunk = new Button(); + private Button btnCleanJunk = new Button(); + private Button btnCleanJunkForever = new Button(); + + // ---------- Tab2 微信 ---------- + private ListView lvWeChat = new ListView(); + private Label lblWeChatStatus = new Label(); + private ProgressBar pbWeChat = new ProgressBar(); + private Button btnScanWeChat = new Button(); + private Button btnCleanWeChat = new Button(); + + // ---------- Tab3 大文件 ---------- + private ListView lvBig = new ListView(); + private Label lblBigStatus = new Label(); + private ProgressBar pbBig = new ProgressBar(); + private Button btnScanBig = new Button(); + private Button btnCleanBig = new Button(); + private TextBox txtMinSizeMB = new TextBox(); + + // ---------- Tab4 重复文件 ---------- + private ListView lvDup = new ListView(); + private Label lblDupStatus = new Label(); + private ProgressBar pbDup = new ProgressBar(); + private Button btnScanDup = new Button(); + private Button btnCleanDup = new Button(); + + // ---------- Tab5 磁盘 ---------- + private ComboBox cboDrives = new ComboBox(); + private Button btnAnalyze = new Button(); + private RichTextBox rtbDisk = new RichTextBox(); + private ProgressBar pbDisk = new ProgressBar(); + + private TabControl tabs = new TabControl(); + + public MainForm() + { + BuildUi(); + } + + // ================= 界面 ================= + private void BuildUi() + { + Text = "ZPclean - 磁盘清理助手"; + ClientSize = new Size(980, 660); + MinimumSize = new Size(900, 600); + StartPosition = FormStartPosition.CenterScreen; + BackColor = Color.FromArgb(245, 245, 245); + Font = new Font("Microsoft YaHei UI", 9F); + + tabs.Dock = DockStyle.Fill; + tabs.Font = new Font("Microsoft YaHei UI", 9.5F); + tabs.TabPages.Add(BuildJunkTab()); + tabs.TabPages.Add(BuildWeChatTab()); + tabs.TabPages.Add(BuildBigTab()); + tabs.TabPages.Add(BuildDupTab()); + tabs.TabPages.Add(BuildDiskTab()); + Controls.Add(tabs); + } + + private Button MakeButton(string text, Color color, int x, int y, EventHandler onClick) + { + var b = new Button + { + Text = text, + Size = new Size(130, 38), + Location = new Point(x, y), + BackColor = color, + ForeColor = Color.White, + FlatStyle = FlatStyle.Flat, + Cursor = Cursors.Hand + }; + b.Click += onClick; + return b; + } + + private ListView MakeListView(params string[] cols) + { + var lv = new ListView + { + Dock = DockStyle.Fill, + View = View.Details, + FullRowSelect = true, + CheckBoxes = true, + GridLines = true, + HideSelection = false + }; + foreach (var c in cols) { lv.Columns.Add(c, -2); } + return lv; + } + + private TabPage BuildJunkTab() + { + var p = new TabPage("垃圾文件"); + p.Padding = new Padding(12); + var top = new Panel { Dock = DockStyle.Top, Height = 90 }; + btnScanJunk = MakeButton("开始扫描垃圾文件", Color.FromArgb(76, 175, 80), 12, 12, (s, e) => ScanJunk()); + btnCleanJunk = MakeButton("移到回收站", Color.FromArgb(33, 150, 243), 152, 12, (s, e) => CleanToRecycle(lvJunk, "垃圾文件")); + btnCleanJunkForever = MakeButton("永久删除", Color.FromArgb(229, 57, 53), 292, 12, (s, e) => CleanForever(lvJunk, "垃圾文件")); + lblJunkStatus = new Label { Location = new Point(12, 60), AutoSize = true, Text = "点击「开始扫描垃圾文件」" }; + top.Controls.Add(btnScanJunk); + top.Controls.Add(btnCleanJunk); + top.Controls.Add(btnCleanJunkForever); + top.Controls.Add(lblJunkStatus); + lvJunk = MakeListView("项目", "文件数", "大小", "路径"); + lvJunk.Columns[1].Width = 90; + lvJunk.Columns[2].Width = 110; + lvJunk.Columns[3].Width = 480; + pbJunk = new ProgressBar { Dock = DockStyle.Bottom, Height = 16 }; + p.Controls.Add(lvJunk); + p.Controls.Add(pbJunk); + p.Controls.Add(top); + return p; + } + + private TabPage BuildWeChatTab() + { + var p = new TabPage("微信缓存"); + p.Padding = new Padding(12); + var top = new Panel { Dock = DockStyle.Top, Height = 90 }; + btnScanWeChat = MakeButton("扫描微信缓存", Color.FromArgb(0, 170, 90), 12, 12, (s, e) => ScanWeChat()); + btnCleanWeChat = MakeButton("移到回收站", Color.FromArgb(33, 150, 243), 152, 12, (s, e) => CleanToRecycle(lvWeChat, "微信缓存")); + lblWeChatStatus = new Label { Location = new Point(12, 60), AutoSize = true, Text = "点击「扫描微信缓存」" }; + top.Controls.Add(btnScanWeChat); + top.Controls.Add(btnCleanWeChat); + top.Controls.Add(lblWeChatStatus); + lvWeChat = MakeListView("缓存目录", "文件数", "大小", "路径"); + lvWeChat.Columns[1].Width = 90; + lvWeChat.Columns[2].Width = 110; + lvWeChat.Columns[3].Width = 480; + pbWeChat = new ProgressBar { Dock = DockStyle.Bottom, Height = 16 }; + p.Controls.Add(lvWeChat); + p.Controls.Add(pbWeChat); + p.Controls.Add(top); + return p; + } + + private TabPage BuildBigTab() + { + var p = new TabPage("大文件"); + p.Padding = new Padding(12); + var top = new Panel { Dock = DockStyle.Top, Height = 90 }; + btnScanBig = MakeButton("扫描大文件", Color.FromArgb(255, 152, 0), 12, 12, (s, e) => ScanBigFiles()); + btnCleanBig = MakeButton("移到回收站", Color.FromArgb(33, 150, 243), 152, 12, (s, e) => CleanToRecycle(lvBig, "大文件")); + var lbl = new Label { Location = new Point(12, 60), AutoSize = true, Text = "阈值(MB):" }; + txtMinSizeMB = new TextBox { Location = new Point(78, 57), Width = 70, Text = "500" }; + top.Controls.Add(btnScanBig); + top.Controls.Add(btnCleanBig); + top.Controls.Add(lbl); + top.Controls.Add(txtMinSizeMB); + lblBigStatus = new Label { Location = new Point(160, 60), AutoSize = true, Text = "" }; + top.Controls.Add(lblBigStatus); + lvBig = MakeListView("文件", "大小", "修改时间", "完整路径"); + lvBig.Columns[1].Width = 110; + lvBig.Columns[2].Width = 150; + lvBig.Columns[3].Width = 460; + pbBig = new ProgressBar { Dock = DockStyle.Bottom, Height = 16 }; + p.Controls.Add(lvBig); + p.Controls.Add(pbBig); + p.Controls.Add(top); + return p; + } + + private TabPage BuildDupTab() + { + var p = new TabPage("重复文件"); + p.Padding = new Padding(12); + var top = new Panel { Dock = DockStyle.Top, Height = 90 }; + btnScanDup = MakeButton("扫描重复文件", Color.FromArgb(156, 39, 176), 12, 12, (s, e) => ScanDuplicates()); + btnCleanDup = MakeButton("移到回收站", Color.FromArgb(33, 150, 243), 152, 12, (s, e) => CleanToRecycle(lvDup, "重复文件")); + lblDupStatus = new Label { Location = new Point(12, 60), AutoSize = true, Text = "只列出重复的文件(每组保留一份)" }; + top.Controls.Add(btnScanDup); + top.Controls.Add(btnCleanDup); + top.Controls.Add(lblDupStatus); + lvDup = MakeListView("文件", "大小", "重复组", "完整路径"); + lvDup.Columns[1].Width = 110; + lvDup.Columns[2].Width = 90; + lvDup.Columns[3].Width = 460; + pbDup = new ProgressBar { Dock = DockStyle.Bottom, Height = 16 }; + p.Controls.Add(lvDup); + p.Controls.Add(pbDup); + p.Controls.Add(top); + return p; + } + + private TabPage BuildDiskTab() + { + var p = new TabPage("磁盘分析"); + p.Padding = new Padding(12); + var top = new Panel { Dock = DockStyle.Top, Height = 60 }; + cboDrives = new ComboBox { Location = new Point(12, 14), Width = 160, DropDownStyle = ComboBoxStyle.DropDownList }; + btnAnalyze = MakeButton("分析磁盘", Color.FromArgb(33, 150, 243), 186, 6, (s, e) => AnalyzeDisk()); + top.Controls.Add(cboDrives); + top.Controls.Add(btnAnalyze); + rtbDisk = new RichTextBox { Dock = DockStyle.Fill, ReadOnly = true, BackColor = Color.White, BorderStyle = BorderStyle.FixedSingle }; + pbDisk = new ProgressBar { Dock = DockStyle.Bottom, Height = 16 }; + p.Controls.Add(rtbDisk); + p.Controls.Add(pbDisk); + p.Controls.Add(top); + foreach (var d in DriveInfo.GetDrives()) + { + try { if (d.IsReady) cboDrives.Items.Add(d.Name); } catch { } + } + if (cboDrives.Items.Count > 0) cboDrives.SelectedIndex = 0; + return p; + } + + // ================= 通用工具 ================= + private sealed class CheckableItem + { + public string Label; + public string Path; + public long Size; + public int Count; + public bool IsDirectory; + } + + private static string HumanSize(long b) + { + if (b < 1024) return b + " B"; + if (b < 1024L * 1024) return (b / 1024.0).ToString("F2") + " KB"; + if (b < 1024L * 1024 * 1024) return (b / (1024.0 * 1024)).ToString("F2") + " MB"; + return (b / (1024.0 * 1024 * 1024)).ToString("F2") + " GB"; + } + + /// 安全遍历:逐目录 try/catch,跳过无权限目录与链接目录(避免死循环) + private static IEnumerable SafeEnumerateFiles(string root, Func skipDir = null) + { + var stack = new Stack(); + stack.Push(root); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + while (stack.Count > 0) + { + string dir = stack.Pop(); + if (!seen.Add(dir)) continue; + string[] files; + try { files = Directory.GetFiles(dir); } + catch { continue; } + foreach (var f in files) yield return f; + string[] subDirs; + try { subDirs = Directory.GetDirectories(dir); } + catch { continue; } + foreach (var sd in subDirs) + { + try + { + var attr = File.GetAttributes(sd); + if ((attr & FileAttributes.ReparsePoint) != 0) continue; // 跳过符号链接/联接 + } + catch { continue; } + if (skipDir != null && skipDir(sd)) continue; + stack.Push(sd); + } + } + } + + private static void SafeSetProgress(ProgressBar bar, int value) + { + if (bar.InvokeRequired) { bar.BeginInvoke(new Action(() => SafeSetProgress(bar, value))); return; } + bar.Value = Math.Max(bar.Minimum, Math.Min(bar.Maximum, value)); + Application.DoEvents(); + } + + private void SetStatus(Label lbl, string text) + { + if (lbl.InvokeRequired) { lbl.BeginInvoke(new Action(() => SetStatus(lbl, text))); return; } + lbl.Text = text; + Application.DoEvents(); + } + + // ================= Tab1 垃圾扫描 ================= + private void ScanJunk() + { + _cancel = false; + _junkItems.Clear(); + lvJunk.Items.Clear(); + SetStatus(lblJunkStatus, "扫描中..."); + Application.DoEvents(); + + var targets = new List<(string name, string path)> + { + ("用户临时文件", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Temp")), + ("系统临时文件", Path.GetTempPath()), + ("IE 缓存", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Microsoft", "Windows", "INetCache")), + ("Windows 更新缓存", @"C:\Windows\SoftwareDistribution\Download"), + ("Edge 缓存", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft", "Edge", "User Data", "Default", "Cache")), + ("Chrome 缓存", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Google", "Chrome", "User Data", "Default", "Cache")), + ("错误报告", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CrashDumps")), + }; + + int idx = 0; + foreach (var t in targets) + { + if (_cancel) break; + idx++; + SafeSetProgress(pbJunk, idx * 100 / targets.Count); + if (!Directory.Exists(t.path)) continue; + long size = 0; int count = 0; + try + { + foreach (var f in SafeEnumerateFiles(t.path)) + { + count++; + try { size += new FileInfo(f).Length; } catch { } + } + } + catch { } + if (count > 0) + { + _junkItems.Add(new CheckableItem { Label = t.name, Path = t.path, Size = size, Count = count, IsDirectory = true }); + var it = new ListViewItem(t.name); + it.SubItems.Add(count.ToString()); + it.SubItems.Add(HumanSize(size)); + it.SubItems.Add(t.path); + it.Checked = true; + it.Tag = _junkItems[_junkItems.Count - 1]; + lvJunk.Items.Add(it); + } + SetStatus(lblJunkStatus, "扫描中... " + t.name); + } + long total = _junkItems.Sum(i => i.Size); + SetStatus(lblJunkStatus, string.Format("完成:{0} 个目录,共 {1}", _junkItems.Count, HumanSize(total))); + MessageBox.Show(this, string.Format("扫描完成:\n\n{0} 个可清理目录\n合计大小:{1}\n\n勾选后可「移到回收站」或「永久删除」", _junkItems.Count, HumanSize(total)), + "扫描完成", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + + // ================= Tab2 微信缓存 ================= + private void ScanWeChat() + { + _cancel = false; + _wechatItems.Clear(); + lvWeChat.Items.Clear(); + SetStatus(lblWeChatStatus, "扫描中..."); + + var roots = new List(); + var docs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); + var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + roots.Add(Path.Combine(docs, "WeChat Files")); // 微信 3.x + roots.Add(Path.Combine(docs, "xwechat_files")); // 微信 4.x + roots.Add(Path.Combine(appData, "Tencent", "WeChat")); + roots.Add(Path.Combine(appData, "Tencent", "xwechat")); + + var cacheNames = new[] { "Cache", "MsgImage", "MsgVideo", "FileTransfer", "Video", "Voice", "Image", "Temp" }; + var found = new List(); + foreach (var root in roots) + { + if (!Directory.Exists(root)) continue; + foreach (var userDir in SafeEnumerateDirs(root)) + { + foreach (var c in cacheNames) + { + var p = Path.Combine(userDir, c); + if (Directory.Exists(p)) found.Add(p); + } + var globalCache = Path.Combine(userDir, "Cache"); + if (Directory.Exists(globalCache) && !found.Contains(globalCache)) found.Add(globalCache); + } + if (found.Count > 0) break; // 找到一套就用那套,避免重复统计 + } + + int idx = 0; + foreach (var p in found) + { + if (_cancel) break; + idx++; + SafeSetProgress(pbWeChat, idx * 100 / Math.Max(1, found.Count)); + long size = 0; int count = 0; + foreach (var f in SafeEnumerateFiles(p)) + { + count++; + try { size += new FileInfo(f).Length; } catch { } + } + if (count == 0) continue; + _wechatItems.Add(new CheckableItem { Label = Path.GetFileName(p), Path = p, Size = size, Count = count, IsDirectory = true }); + var it = new ListViewItem(Path.GetFileName(p)); + it.SubItems.Add(count.ToString()); + it.SubItems.Add(HumanSize(size)); + it.SubItems.Add(p); + it.Checked = true; + it.Tag = _wechatItems[_wechatItems.Count - 1]; + lvWeChat.Items.Add(it); + } + + if (_wechatItems.Count == 0) + { + SetStatus(lblWeChatStatus, "没找到微信缓存目录(微信 3.x/4.x 都试过了)"); + MessageBox.Show(this, "没找到微信缓存目录。\n可能微信没装在这台电脑,或数据目录被改过。", + "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); + return; + } + long total = _wechatItems.Sum(i => i.Size); + SetStatus(lblWeChatStatus, string.Format("完成:{0} 个缓存目录,共 {1}", _wechatItems.Count, HumanSize(total))); + MessageBox.Show(this, string.Format("扫描完成:\n\n{0} 个缓存目录\n合计:{1}", _wechatItems.Count, HumanSize(total)), + "扫描完成", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + + private static IEnumerable SafeEnumerateDirs(string root) + { + var stack = new Stack(); + stack.Push(root); + int depth = 0; + while (stack.Count > 0 && depth < 200) + { + string dir = stack.Pop(); + string[] subs; + try { subs = Directory.GetDirectories(dir); } + catch { continue; } + foreach (var s in subs) + { + yield return s; + stack.Push(s); + } + depth++; + } + } + + // ================= Tab3 大文件 ================= + private void ScanBigFiles() + { + _cancel = false; + _bigItems.Clear(); + lvBig.Items.Clear(); + SetStatus(lblBigStatus, "扫描中..."); + + int minMB = 500; + if (!int.TryParse(txtMinSizeMB.Text.Trim(), out minMB) || minMB <= 0) minMB = 500; + long minSize = (long)minMB * 1024 * 1024; + + string userPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + var found = new List(); + int total = 0, hits = 0; + var sw = Stopwatch.StartNew(); + foreach (var f in SafeEnumerateFiles(userPath)) + { + if (_cancel) break; + total++; + if (total % 200 == 0) + { + SafeSetProgress(pbBig, (int)(total % 100)); + SetStatus(lblBigStatus, string.Format("扫描中... 已检查 {0} 个文件,用时 {1:0}s", total, sw.Elapsed.TotalSeconds)); + } + try + { + var fi = new FileInfo(f); + if (fi.Length < minSize) continue; + hits++; + found.Add(new CheckableItem { Label = fi.Name, Path = fi.FullName, Size = fi.Length, IsDirectory = false }); + } + catch { } + } + SafeSetProgress(pbBig, 100); + foreach (var it in found.OrderByDescending(i => i.Size).Take(500)) + { + var lv = new ListViewItem(it.Label); + lv.SubItems.Add(HumanSize(it.Size)); + try { lv.SubItems.Add(File.GetLastWriteTime(it.Path).ToString("yyyy-MM-dd HH:mm")); } catch { lv.SubItems.Add("-"); } + lv.SubItems.Add(it.Path); + lv.Tag = it; + _bigItems.Add(it); + lvBig.Items.Add(lv); + } + SetStatus(lblBigStatus, string.Format("完成:检查 {0} 个文件,命中 {1} 个(≥{2}MB),用时 {3:0}s", total, hits, minMB, sw.Elapsed.TotalSeconds)); + MessageBox.Show(this, string.Format("扫描完成:\n\n检查 {0} 个文件\n命中 {1} 个大文件(≥{2}MB)\n用时 {3:0} 秒\n\n(列表最多显示 500 条)", total, hits, minMB, sw.Elapsed.TotalSeconds), + "扫描完成", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + + // ================= Tab4 重复文件 ================= + private void ScanDuplicates() + { + _cancel = false; + _dupItems.Clear(); + lvDup.Items.Clear(); + SetStatus(lblDupStatus, "扫描中(先按大小分组,再算哈希,会慢一些)..."); + + string userPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + var bySize = new Dictionary>(); + int total = 0; + var sw = Stopwatch.StartNew(); + foreach (var f in SafeEnumerateFiles(userPath)) + { + if (_cancel) break; + total++; + if (total % 200 == 0) + { + SafeSetProgress(pbDup, (int)(total % 100)); + SetStatus(lblDupStatus, string.Format("第 1 步:按大小分组... {0} 个文件,用时 {1:0}s", total, sw.Elapsed.TotalSeconds)); + } + try + { + var len = new FileInfo(f).Length; + if (len <= 0) continue; + if (!bySize.TryGetValue(len, out var list)) { list = new List(); bySize[len] = list; } + list.Add(f); + } + catch { } + } + + var candidates = bySize.Where(kv => kv.Value.Count > 1).ToList(); + int groupIdx = 0; + int dupFiles = 0; + foreach (var kv in candidates) + { + if (_cancel) break; + groupIdx++; + SafeSetProgress(pbDup, (int)(groupIdx * 100 / Math.Max(1, candidates.Count))); + SetStatus(lblDupStatus, string.Format("第 2 步:计算哈希 {0}/{1} 组,用时 {2:0}s", groupIdx, candidates.Count, sw.Elapsed.TotalSeconds)); + var byHash = new Dictionary>(); + foreach (var f in kv.Value) + { + try + { + string h = Md5(f); + if (string.IsNullOrEmpty(h)) continue; + if (!byHash.TryGetValue(h, out var l2)) { l2 = new List(); byHash[h] = l2; } + l2.Add(f); + } + catch { } + } + foreach (var g in byHash.Where(x => x.Value.Count > 1)) + { + // 每组保留最早修改的一个,其余列为可清理 + var ordered = g.Value.OrderBy(p => { try { return File.GetLastWriteTime(p); } catch { return DateTime.MinValue; } }).ToList(); + for (int i = 1; i < ordered.Count; i++) + { + var it = new CheckableItem { Label = Path.GetFileName(ordered[i]), Path = ordered[i], Size = kv.Key, IsDirectory = false }; + _dupItems.Add(it); + dupFiles++; + var lv = new ListViewItem(it.Label); + lv.SubItems.Add(HumanSize(kv.Key)); + lv.SubItems.Add(g.Value.Count.ToString()); + lv.SubItems.Add(ordered[i]); + lv.Tag = it; + lvDup.Items.Add(lv); + } + } + } + SafeSetProgress(pbDup, 100); + SetStatus(lblDupStatus, string.Format("完成:{0} 组重复,可清理 {1} 个,用时 {2:0}s", candidates.Count, dupFiles, sw.Elapsed.TotalSeconds)); + MessageBox.Show(this, string.Format("扫描完成:\n\n重复组:{0}\n可清理重复文件:{1} 个\n用时 {2:0} 秒\n\n(每组保留修改时间最早的一份,其余已勾选)", candidates.Count, dupFiles, sw.Elapsed.TotalSeconds), + "扫描完成", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + + private static string Md5(string path) + { + try + { + using (var md5 = MD5.Create()) + using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + return BitConverter.ToString(md5.ComputeHash(fs)).Replace("-", "").ToLowerInvariant(); + } + catch { return ""; } + } + + // ================= Tab5 磁盘分析 ================= + private void AnalyzeDisk() + { + rtbDisk.Clear(); + if (cboDrives.SelectedItem == null) return; + try + { + var drive = new DriveInfo(cboDrives.SelectedItem.ToString()); + long total = drive.TotalSize, free = drive.TotalFreeSpace, used = total - free; + double pct = total > 0 ? (double)used / total * 100 : 0; + rtbDisk.AppendText("磁盘空间分析\n\n"); + rtbDisk.AppendText("盘符:" + drive.Name + " " + drive.VolumeLabel + "\n"); + rtbDisk.AppendText("格式:" + drive.DriveFormat + "\n\n"); + rtbDisk.AppendText("总容量:" + HumanSize(total) + "\n"); + rtbDisk.AppendText("已使用:" + HumanSize(used) + string.Format("({0:0.0}%)", pct) + "\n"); + rtbDisk.AppendText("可用:" + HumanSize(free) + string.Format("({0:0.0}%)", 100 - pct) + "\n\n"); + SafeSetProgress(pbDisk, (int)pct); + } + catch (Exception ex) + { + MessageBox.Show(this, "分析失败:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + // ================= 清理 ================= + private List CheckedItems(ListView lv) + { + var list = new List(); + foreach (ListViewItem it in lv.Items) + { + if (it.Checked && it.Tag is CheckableItem) list.Add((CheckableItem)it.Tag); + } + return list; + } + + private void CleanToRecycle(ListView lv, string label) + { + var items = CheckedItems(lv); + if (items.Count == 0) { MessageBox.Show(this, "请先勾选要清理的条目。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } + long total = items.Sum(i => i.Size); + if (MessageBox.Show(this, string.Format("将把 {0} 项({1})移到【回收站】。\n\n放到回收站后可以随时还原,确定继续?", items.Count, HumanSize(total)), + "确认清理", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes) return; + + int ok = 0, fail = 0; + foreach (var it in items) + { + try + { + if (it.IsDirectory && Directory.Exists(it.Path)) + { + foreach (var f in SafeEnumerateFiles(it.Path)) TryRecycle(f, ref ok, ref fail); + try { Directory.Delete(it.Path, true); } catch { } + } + else if (File.Exists(it.Path)) TryRecycle(it.Path, ref ok, ref fail); + } + catch { fail++; } + } + MessageBox.Show(this, string.Format("完成:成功 {0} 个,失败 {1} 个(失败多为占用中或无权限)", ok, fail), + "清理结果", MessageBoxButtons.OK, MessageBoxIcon.Information); + lv.Items.Clear(); + } + + private void CleanForever(ListView lv, string label) + { + var items = CheckedItems(lv); + if (items.Count == 0) { MessageBox.Show(this, "请先勾选要清理的条目。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } + long total = items.Sum(i => i.Size); + if (MessageBox.Show(this, string.Format("⚠ 永久删除 {0} 项({1})!\n\n【不可恢复】,确定?", items.Count, HumanSize(total)), + "确认永久删除", MessageBoxButtons.YesNo, MessageBoxIcon.Error) != DialogResult.Yes) return; + if (MessageBox.Show(this, "再确认一次:真的要永久删除吗?", "最后确认", MessageBoxButtons.YesNo, MessageBoxIcon.Error) != DialogResult.Yes) return; + + int ok = 0, fail = 0; + foreach (var it in items) + { + try + { + if (it.IsDirectory && Directory.Exists(it.Path)) { Directory.Delete(it.Path, true); ok++; } + else if (File.Exists(it.Path)) { File.Delete(it.Path); ok++; } + } + catch { fail++; } + } + MessageBox.Show(this, string.Format("完成:成功 {0} 项,失败 {1} 项", ok, fail), "清理结果", MessageBoxButtons.OK, MessageBoxIcon.Information); + lv.Items.Clear(); + } + + private static void TryRecycle(string file, ref int ok, ref int fail) + { + try + { + FileSystem.DeleteFile(file, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin); + ok++; + } + catch { fail++; } + } + + } +} diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..47ca23f --- /dev/null +++ b/Program.cs @@ -0,0 +1,16 @@ +using System; +using System.Windows.Forms; + +namespace ZPclean +{ + internal static class Program + { + [STAThread] + private static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new MainForm()); + } + } +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..dfb404c --- /dev/null +++ b/README.md @@ -0,0 +1,54 @@ +# ZPclean · 磁盘清理助手(重写版 2026-10-30) + +一个本地 Windows 桌面工具:**扫描 → 勾选 → 清理**,全程不联网、不提权。 + +## 功能(5 个页签) + +| 页签 | 作用 | +|---|---| +| 垃圾文件 | 扫 用户/系统临时目录、IE 缓存、Windows 更新缓存、Edge/Chrome 缓存、崩溃转储 | +| 微信缓存 | 自动探测微信 3.x `WeChat Files` 与 4.x `xwechat_files`、AppData\Tencent 下的缓存子目录 | +| 大文件 | 按阈值(默认 500MB,可改)扫用户目录,列出大文件 | +| 重复文件 | **先按大小分组,再只对同大小组算 MD5** → 快很多;每组保留修改时间最早的一份,其余列出待清理 | +| 磁盘分析 | 各盘容量/已用/可用 | + +## 清理方式 + +- **移到回收站**(默认):可还原 +- **永久删除**:两次确认才执行 + +## 相比初版修掉的问题 + +1. **界面中文全是乱码** → 全部文案重写为 UTF-8 +2. **大文件/重复文件扫描遇到无权限目录直接抛异常中断** → 改为安全递归(逐目录 try/catch,跳过链接目录防死循环) +3. **进度条不动** → 实时进度 + 已扫描文件数 + 用时 +4. **大文件/重复文件的状态显示串到「C盘垃圾」页** → 各页归位 +5. **只扫不删**(名字叫清理助手却没有清理)→ 增加回收站/永久删除 +6. **重复文件全盘算 MD5**(极慢)→ 改为先按大小分组 +7. **微信目录只认老路径** → 兼容 3.x / 4.x / AppData +8. 清掉了初版里残留的三套失败修复尝试(FixPath 工程 / fix.ps1 / debug.txt / UTF8 垃圾文件 / bin+obj 编译产物) + +## 构建(Windows,需 .NET 8 SDK) + +```powershell +# 方式一:一键脚本(推荐) +.\build.ps1 + +# 方式二:手动 +dotnet build -c Release +dotnet publish -c Release -r win-x64 --self-contained false -p:PublishSingleFile=true -o .\publish +``` + +产物:`publish\ZPclean.exe`(双击 `启动.bat` 也会自动优先用它) + +> 想做成「不依赖装 .NET」的绿色版:把 `--self-contained false` 改成 `true`(exe 约 150MB)。 + +## 安全说明 + +- 只读扫描 + 明确的删除确认;**永久删除要连点两次确认** +- 不联网、不写注册表、不装服务、不提权 +- 建议第一次用先只跑「扫描」,看看列表再勾选 + +## License + +MIT diff --git a/ZPclean.csproj b/ZPclean.csproj new file mode 100644 index 0000000..fe3fb04 --- /dev/null +++ b/ZPclean.csproj @@ -0,0 +1,16 @@ + + + + WinExe + net8.0-windows + ZPclean + ZPclean + disable + true + disable + + + en + + + diff --git a/build.ps1 b/build.ps1 new file mode 100644 index 0000000..15de496 --- /dev/null +++ b/build.ps1 @@ -0,0 +1,22 @@ +# ZPclean 构建脚本(Windows 上执行) +# 用法:右键 → 使用 PowerShell 运行;或在 PowerShell 里: .\build.ps1 +$ErrorActionPreference = "Stop" +$here = Split-Path -Parent $MyInvocation.MyCommand.Path +Set-Location $here + +Write-Host "== 检查 dotnet SDK ==" -ForegroundColor Cyan +$ver = dotnet --version +Write-Host "SDK 版本: $ver" + +Write-Host "== 还原依赖 ==" -ForegroundColor Cyan +dotnet restore + +Write-Host "== 编译(Release)==" -ForegroundColor Cyan +dotnet build -c Release -warnaserror:false + +Write-Host "== 发布单文件 exe ==" -ForegroundColor Cyan +dotnet publish -c Release -r win-x64 --self-contained false -p:PublishSingleFile=true -o ".\publish" + +Write-Host "" +Write-Host "完成。产物在: $here\publish\ZPclean.exe" -ForegroundColor Green +Write-Host "(自包含版:把上面命令里的 --self-contained false 改成 true,exe 更大但不依赖装 .NET)" diff --git a/启动.bat b/启动.bat new file mode 100644 index 0000000..7189bd0 --- /dev/null +++ b/启动.bat @@ -0,0 +1,11 @@ +@echo off +chcp 65001 > nul +cd /d "%~dp0" +if exist "publish\ZPclean.exe" ( + echo [ZPclean] 使用已发布的版本... + start "" "publish\ZPclean.exe" +) else ( + echo [ZPclean] 还没发布,先运行 build.ps1 生成 exe;这里用 dotnet run 启动... + dotnet run +) +if errorlevel 1 pause