// 大文件拆分合并 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法(net48 自带 csc 可编译) // 功能:按体积把大文件拆成 .partN + 清单;合并时校验 SHA256,坏了拒绝还原 // 边界:流式处理,4MB 缓冲,几 GB 的文件也只占这点内存;拆完原文件不动 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 SplitOps { public const int BufSize = 4 * 1024 * 1024; public class SplitResult { public string FirstPart; // 第一个分卷的完整路径 public string Manifest; // 清单文件路径 public int Parts; public long SourceLength; public string Sha256; public List PartFiles = new List(); } /* 拆分:partSize 至少 64KB;输出 outDir(为空时放源文件旁的「拆分_<名>」子目录) */ public static SplitResult Split(string file, long partSize, string outDir) { if (!File.Exists(file)) throw new IOException("文件不存在:" + file); if (partSize < 64 * 1024) throw new IOException("每卷至少 64KB。"); string name = Path.GetFileName(file); if (string.IsNullOrEmpty(outDir)) outDir = Path.Combine(Path.GetDirectoryName(file), "拆分_" + Path.GetFileNameWithoutExtension(file)); Directory.CreateDirectory(outDir); /* 重跑先清掉同名旧分卷:上次拆 100MB 这次拆 50MB,残留的 partN 会拼出坏文件 */ foreach (string old in Directory.GetFiles(outDir, Path.GetFileName(file) + ".part*")) File.Delete(old); if (File.Exists(Path.Combine(outDir, Path.GetFileName(file) + ".manifest.txt"))) File.Delete(Path.Combine(outDir, Path.GetFileName(file) + ".manifest.txt")); SplitResult r = new SplitResult(); r.SourceLength = new FileInfo(file).Length; r.Sha256 = Sha256File(file); List sizes = new List(); using (FileStream src = File.OpenRead(file)) { int part = 1; while (true) { string partFile = Path.Combine(outDir, name + ".part" + part.ToString("000")); long written = 0; byte[] buf = new byte[BufSize]; using (FileStream dst = File.Create(partFile)) { while (written < partSize) { int want = (int)Math.Min(buf.Length, partSize - written); int got = src.Read(buf, 0, want); if (got <= 0) break; dst.Write(buf, 0, got); written += got; } } if (written == 0) { File.Delete(partFile); // 整除时多算出的空卷 break; } r.PartFiles.Add(partFile); sizes.Add(Path.GetFileName(partFile) + "|" + written); r.FirstPart = partFile; part++; if (written < partSize) break; // 读完了 } } if (r.PartFiles.Count == 0) throw new IOException("源文件是空的,不需要拆。"); r.Parts = r.PartFiles.Count; r.Manifest = Path.Combine(outDir, name + ".manifest.txt"); StringBuilder sb = new StringBuilder(); sb.AppendLine("GreenTool 拆分清单 v1"); sb.AppendLine("file=" + name); sb.AppendLine("size=" + r.SourceLength); sb.AppendLine("sha256=" + r.Sha256); sb.AppendLine("parts=" + r.Parts); foreach (string s in sizes) sb.AppendLine(s); File.WriteAllText(r.Manifest, sb.ToString(), new UTF8Encoding(false)); return r; } /* 清单解析;传清单文件或任意 .part 文件(沿目录找清单)都可以 */ public static Dictionary ReadManifest(string anyPath) { string mf = anyPath; if (!mf.EndsWith(".manifest.txt", StringComparison.OrdinalIgnoreCase)) { string guess = ManifestForPart(anyPath); if (File.Exists(guess)) mf = guess; } if (!File.Exists(mf)) throw new IOException("找不到清单文件(.manifest.txt)。"); Dictionary kv = new Dictionary(); foreach (string line in File.ReadAllLines(mf)) { int i = line.IndexOf('='); if (i <= 0) continue; kv[line.Substring(0, i)] = line.Substring(i + 1); } if (!kv.ContainsKey("file") || !kv.ContainsKey("parts") || !kv.ContainsKey("sha256")) throw new IOException("清单不完整,不是本工具生成的。"); return kv; } public static string ManifestForPart(string partFile) { string name = Path.GetFileName(partFile); int dot = name.LastIndexOf(".part", StringComparison.OrdinalIgnoreCase); string baseName = dot > 0 ? name.Substring(0, dot) : name; return Path.Combine(Path.GetDirectoryName(partFile), baseName + ".manifest.txt"); } /* 合并:清单 + 输出路径。逐卷校验在总校验之外还做了体积检查;SHA256 不符删产物 */ public static MergeResult Merge(Dictionary mf, string outDir, string outFile) { string name = mf["file"]; long wantSize = long.Parse(mf["size"]); int parts = int.Parse(mf["parts"]); string wantSha = mf["sha256"]; if (string.IsNullOrEmpty(outFile)) outFile = Path.Combine(outDir, name); /* 同名文件一律改名,绝不覆盖:万一用户选错目录,不能把已有文件毁了 */ int k = 2; while (File.Exists(outFile)) { outFile = Path.Combine(Path.GetDirectoryName(outFile), Path.GetFileNameWithoutExtension(name) + " (" + k + ")" + Path.GetExtension(name)); k++; } long total = 0; byte[] buf = new byte[BufSize]; using (SHA256 sha = SHA256.Create()) using (FileStream dst = File.Create(outFile)) { for (int i = 1; i <= parts; i++) { string part = Path.Combine(outDir, name + ".part" + i.ToString("000")); if (!File.Exists(part)) throw new IOException("缺分卷:" + Path.GetFileName(part)); using (FileStream src = File.OpenRead(part)) { int got; while ((got = src.Read(buf, 0, buf.Length)) > 0) { dst.Write(buf, 0, got); sha.TransformBlock(buf, 0, got, null, 0); total += got; } } } sha.TransformFinalBlock(new byte[0], 0, 0); string gotSha = Hex(sha.Hash); if (gotSha != wantSha) { dst.Close(); File.Delete(outFile); throw new IOException("合并完成但校验不符:分卷有损坏或缺页。已删除产物,请检查分卷。"); } } if (total != wantSize) throw new IOException("合并体积 " + total + " 与清单 " + wantSize + " 不符。"); MergeResult mr = new MergeResult(); mr.File = outFile; mr.Length = total; return mr; } private static bool SameFile(string f, long len) { try { return new FileInfo(f).Length == len; } catch { return false; } } public class MergeResult { public string File; public long Length; } public static string Sha256File(string file) { using (FileStream fs = File.OpenRead(file)) using (SHA256 sha = SHA256.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 class FileSplitForm : Form { private TextBox txtFile; private Button btnBrowse; private ComboBox cmbSize; private Button btnSplit; private TextBox txtManifest; private Button btnMfBrowse; private TextBox txtOut; private Button btnMerge; private Label lblStatus; private ProgressBar progress; private BackgroundWorker worker; private int mode; // 0 split / 1 merge private object jobArg; public FileSplitForm() { InitUi(); worker = new BackgroundWorker(); 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(720, 420); this.MinimumSize = new Size(640, 380); this.AllowDrop = true; this.DragEnter += new DragEventHandler(FormDragEnter); this.DragDrop += new DragEventHandler(FormDragDrop); int x = 20, y = 16; Label lblTitle = new Label(); lblTitle.Text = "把大文件拆成小卷方便传网盘 / 邮件;合并时校验 SHA256,分卷坏了不会悄悄还原出坏文件"; lblTitle.Location = new Point(x, y); lblTitle.AutoSize = true; lblTitle.ForeColor = Color.FromArgb(120, 130, 124); this.Controls.Add(lblTitle); y += 32; Label l1 = new Label(); l1.Text = "要拆分的文件"; l1.Location = new Point(x, y); l1.AutoSize = true; this.Controls.Add(l1); txtFile = new TextBox(); txtFile.Location = new Point(x + 100, y - 3); txtFile.Size = new Size(440, 26); this.Controls.Add(txtFile); btnBrowse = new Button(); btnBrowse.Text = "浏览…"; btnBrowse.Location = new Point(x + 552, y - 4); btnBrowse.Size = new Size(120, 28); btnBrowse.Click += new EventHandler(BrowseClick); this.Controls.Add(btnBrowse); y += 40; Label l2 = new Label(); l2.Text = "每卷大小"; l2.Location = new Point(x, y + 4); l2.AutoSize = true; this.Controls.Add(l2); cmbSize = new ComboBox(); cmbSize.DropDownStyle = ComboBoxStyle.DropDownList; cmbSize.Items.AddRange(new object[] { "10 MB", "50 MB", "100 MB", "500 MB", "1 GB" }); cmbSize.SelectedIndex = 2; cmbSize.Location = new Point(x + 100, y); cmbSize.Size = new Size(110, 26); this.Controls.Add(cmbSize); btnSplit = new Button(); btnSplit.Text = "开始拆分"; btnSplit.Location = new Point(x + 240, y - 2); btnSplit.Size = new Size(140, 34); btnSplit.BackColor = Color.FromArgb(0, 145, 88); btnSplit.ForeColor = Color.White; btnSplit.FlatStyle = FlatStyle.Flat; btnSplit.Click += new EventHandler(SplitClick); this.Controls.Add(btnSplit); y += 62; Label l3 = new Label(); l3.Text = "合并:选清单或任意分卷"; l3.Location = new Point(x, y); l3.AutoSize = true; this.Controls.Add(l3); txtManifest = new TextBox(); txtManifest.Location = new Point(x + 160, y - 3); txtManifest.Size = new Size(380, 26); this.Controls.Add(txtManifest); btnMfBrowse = new Button(); btnMfBrowse.Text = "浏览…"; btnMfBrowse.Location = new Point(x + 552, y - 4); btnMfBrowse.Size = new Size(120, 28); btnMfBrowse.Click += new EventHandler(MfBrowseClick); this.Controls.Add(btnMfBrowse); y += 40; Label l4 = new Label(); l4.Text = "输出到"; l4.Location = new Point(x, y + 4); l4.AutoSize = true; this.Controls.Add(l4); txtOut = new TextBox(); txtOut.Location = new Point(x + 100, y - 3); txtOut.Size = new Size(440, 26); this.Controls.Add(txtOut); btnMerge = new Button(); btnMerge.Text = "开始合并"; btnMerge.Location = new Point(x + 552, y - 6); btnMerge.Size = new Size(120, 32); btnMerge.Click += new EventHandler(MergeClick); this.Controls.Add(btnMerge); y += 56; lblStatus = new Label(); lblStatus.Text = "把文件拖到窗口上开始拆分;合并时把 .manifest.txt 或任意 .partN 拖进来"; lblStatus.Location = new Point(x, y); lblStatus.AutoSize = true; lblStatus.ForeColor = Color.FromArgb(120, 130, 124); this.Controls.Add(lblStatus); y += 30; progress = new ProgressBar(); progress.Location = new Point(x, y); progress.Size = new Size(652, 22); this.Controls.Add(progress); } private long PartSize() { switch (cmbSize.SelectedIndex) { case 0: return 10L * 1024 * 1024; case 1: return 50L * 1024 * 1024; case 3: return 500L * 1024 * 1024; case 4: return 1024L * 1024 * 1024; default: return 100L * 1024 * 1024; } } private void BrowseClick(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "选择要拆分的大文件"; if (dlg.ShowDialog(this) == DialogResult.OK) txtFile.Text = dlg.FileName; } private void MfBrowseClick(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "选择清单或任意分卷"; dlg.Filter = "清单或分卷 (*.manifest.txt;*.part*)|*.manifest.txt;*.part*|所有文件 (*.*)|*.*"; if (dlg.ShowDialog(this) == DialogResult.OK) txtManifest.Text = dlg.FileName; } 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) return; if (paths[0].EndsWith(".manifest.txt", StringComparison.OrdinalIgnoreCase) || paths[0].IndexOf(".part", StringComparison.OrdinalIgnoreCase) >= 0) { txtManifest.Text = paths[0]; } else { txtFile.Text = paths[0]; } } private void SplitClick(object sender, EventArgs e) { string f = (txtFile.Text ?? "").Trim(); if (!File.Exists(f)) { lblStatus.ForeColor = Color.FromArgb(200, 50, 50); lblStatus.Text = "先选一个存在的文件。"; return; } Start(0, new object[] { f, PartSize() }); } private void MergeClick(object sender, EventArgs e) { string mf = (txtManifest.Text ?? "").Trim(); if (mf.Length == 0 || !File.Exists(mf)) { lblStatus.ForeColor = Color.FromArgb(200, 50, 50); lblStatus.Text = "选清单文件(.manifest.txt)或任意一个分卷。"; return; } Start(1, new object[] { mf, (txtOut.Text ?? "").Trim() }); } private void Start(int m, object arg) { mode = m; jobArg = arg; btnSplit.Enabled = false; btnMerge.Enabled = false; progress.Style = ProgressBarStyle.Marquee; progress.MarqueeAnimationSpeed = 40; worker.RunWorkerAsync(); } private void WorkerDoWork(object sender, DoWorkEventArgs e) { object[] a = (object[])jobArg; if (mode == 0) e.Result = SplitOps.Split((string)a[0], (long)a[1], null); else { Dictionary mf = SplitOps.ReadManifest((string)a[0]); string outDir = (string)a[1]; if (string.IsNullOrEmpty(outDir)) outDir = Path.GetDirectoryName((string)a[0]); else if (!Directory.Exists(outDir)) Directory.CreateDirectory(outDir); e.Result = SplitOps.Merge(mf, outDir, null); } } private void WorkerDone(object sender, RunWorkerCompletedEventArgs e) { btnSplit.Enabled = true; btnMerge.Enabled = true; progress.Style = ProgressBarStyle.Blocks; progress.MarqueeAnimationSpeed = 0; progress.Value = 0; if (e.Error != null) { lblStatus.ForeColor = Color.FromArgb(200, 50, 50); lblStatus.Text = e.Error.Message; return; } lblStatus.ForeColor = Color.FromArgb(0, 145, 88); if (mode == 0) { SplitOps.SplitResult r = (SplitOps.SplitResult)e.Result; lblStatus.Text = "拆分完成:" + r.Parts + " 卷 + 清单,输出在 " + Path.GetDirectoryName(r.FirstPart) + "。原文件没动。"; } else { SplitOps.MergeResult r = (SplitOps.MergeResult)e.Result; lblStatus.Text = "合并完成,SHA256 校验通过:" + r.File; } } } // ───────────────────────── 自测 ───────────────────────── public static class SplitSelfTest { 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-split-" + Guid.NewGuid().ToString("N").Substring(0, 8)) : dir; try { Directory.CreateDirectory(baseDir); // 源文件 2.5 MB(跨卷边界;卷 512KB → 5 卷) string src = Path.Combine(baseDir, "大文件 测试.bin"); byte[] data = new byte[2 * 1024 * 1024 + 512 * 1024 + 12345]; for (int i = 0; i < data.Length; i++) data[i] = (byte)((i * 131 + 17) & 0xFF); File.WriteAllBytes(src, data); string wantSha = SplitOps.Sha256File(src); SplitOps.SplitResult r = SplitOps.Split(src, 512 * 1024, null); Check("卷数(2.5MB+ / 512KB)", r.Parts, 6); Check("清单已生成", File.Exists(r.Manifest), true); Check("源文件没被改动", SplitOps.Sha256File(src), wantSha); Dictionary mf = SplitOps.ReadManifest(r.Manifest); Check("清单读回体积", mf["size"], ((long)data.Length).ToString()); Check("清单读回卷数", mf["parts"], "6"); // 卷体积:前 5 卷正好 512KB,末卷补零头 long firstLen = new FileInfo(r.PartFiles[0]).Length; long lastLen = new FileInfo(r.PartFiles[5]).Length; Check("满卷 512KB", firstLen, 512L * 1024); Check("末卷零头", lastLen, data.Length - 5L * 512 * 1024); // 整除场景:恰好 3 卷,不产生空卷 string src2 = Path.Combine(baseDir, "exact.bin"); File.WriteAllBytes(src2, new byte[3 * 512 * 1024]); SplitOps.SplitResult r2 = SplitOps.Split(src2, 512 * 1024, null); Check("整除不产生空卷", r2.Parts, 3); // 合并还原(输出到别的目录) string outDir = Path.Combine(baseDir, "out"); Directory.CreateDirectory(outDir); string partDir = Path.GetDirectoryName(r.FirstPart); SplitOps.MergeResult m = SplitOps.Merge(mf, partDir, Path.Combine(outDir, "还原.bin")); Check("还原体积", m.Length, (long)data.Length); Check("还原内容一致", SplitOps.Sha256File(m.File), wantSha); // 传「任意分卷」也能找到清单 Dictionary mf2 = SplitOps.ReadManifest(r.PartFiles[3]); Check("从分卷找到清单", mf2["sha256"], wantSha); // 破坏一个分卷 → 合并必须拒绝并删产物 string victim = r.PartFiles[1]; byte[] vb = File.ReadAllBytes(victim); vb[100] ^= 0xFF; File.WriteAllBytes(victim, vb); bool threw = false; string badOut = Path.Combine(outDir, "bad.bin"); try { SplitOps.Merge(mf, partDir, badOut); } catch { threw = true; } Check("损坏分卷被拒绝", threw ? "threw" : "silent", "threw"); Check("坏产物已删除", File.Exists(badOut), false); // 缺卷也要明确报错 Dictionary mf3 = new Dictionary(mf); mf3["sha256"] = wantSha; string gone = Path.Combine(partDir, "大文件 测试.bin.part999"); threw = false; Dictionary mf4 = new Dictionary(mf); mf4["parts"] = "999"; try { SplitOps.Merge(mf4, partDir, Path.Combine(outDir, "x.bin")); } catch { threw = true; } Check("缺卷明确报错", threw ? "threw" : "silent", "threw"); // 小卷下限 string tiny = Path.Combine(baseDir, "tiny.txt"); File.WriteAllBytes(tiny, new byte[100]); threw = false; try { SplitOps.Split(tiny, 1024, null); } catch { threw = true; } Check("小于 64KB 拒绝", 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-filesplit.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(SplitSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FileSplitForm()); } } }