// 压缩解压 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法 // 功能:把文件/文件夹打成一个 zip;解压 zip(含中文文件名兼容、zip64、拖放) // 边界:只做 zip 格式(rar/7z 不做);带密码的包不破解,会明确提示;不跟随符号链接 // 兼容:老 zip 里的 GBK 文件名能正确还原;自己写的包用 UTF-8 + 通用标志位 11,Win/Mac/Linux 都不乱码 using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.IO.Compression; using System.Text; using System.Windows.Forms; namespace GreenToolbox { // ---------- CRC32 ---------- public static class ZipCrc { static uint[] _tab; static uint[] Tab() { if (_tab != null) return _tab; uint[] t = new uint[256]; for (uint i = 0; i < 256; i++) { uint c = i; for (int k = 0; k < 8; k++) c = (c & 1) != 0 ? (0xEDB88320u ^ (c >> 1)) : (c >> 1); t[i] = c; } _tab = t; return t; } // 可以分块累计:把上一次的返回值再传进来 public static uint Update(uint crc, byte[] buf, int off, int len) { uint[] t = Tab(); uint c = crc ^ 0xFFFFFFFFu; for (int i = 0; i < len; i++) c = t[(c ^ buf[off + i]) & 0xFF] ^ (c >> 8); return c ^ 0xFFFFFFFFu; } } public class ZipItem { public string Name; public bool IsDir; public long Size; // 解压后大小 public long Packed; // 压缩后大小 public int Method; // 0 = store, 8 = deflate public uint Crc; public int Flags; public long LocalOffset; public ushort DosTime; public ushort DosDate; public bool Encrypted { get { return (Flags & 1) != 0; } } public bool Supported { get { return Method == 0 || Method == 8; } } public override string ToString() { return Name; } } public class ZipWriteItem { public string Source; // 磁盘上的真实路径 public string Name; // 包里的名字,用 / 分隔,目录以 / 结尾 public bool IsDir; public long Size; } // ---------- 读 ---------- public static class ZipReader { public static ushort U16(byte[] b, int p) { return (ushort)(b[p] | (b[p + 1] << 8)); } public static uint U32(byte[] b, int p) { return (uint)(b[p] | (b[p + 1] << 8) | (b[p + 2] << 16) | (b[p + 3] << 24)); } public static ulong U64(byte[] b, int p) { return (ulong)U32(b, p) | ((ulong)U32(b, p + 4) << 32); } public static void W16(Stream s, int v) { s.WriteByte((byte)(v & 0xFF)); s.WriteByte((byte)((v >> 8) & 0xFF)); } public static void W32(Stream s, long v) { for (int i = 0; i < 4; i++) s.WriteByte((byte)((v >> (8 * i)) & 0xFF)); } public static void W64(Stream s, long v) { for (int i = 0; i < 8; i++) s.WriteByte((byte)((v >> (8 * i)) & 0xFF)); } // 中文名解码:优先看通用标志位 11;没置位的老包按「严格 UTF-8 试一次,不行就 GBK」 public static string DecodeName(byte[] raw, int flags) { if (raw == null || raw.Length == 0) return ""; bool ascii = true; for (int i = 0; i < raw.Length; i++) if (raw[i] > 0x7F) { ascii = false; break; } if (ascii) return Encoding.ASCII.GetString(raw); if ((flags & 0x800) != 0) return Encoding.UTF8.GetString(raw); try { UTF8Encoding strict = new UTF8Encoding(false, true); return strict.GetString(raw); } catch { } try { return Encoding.GetEncoding(936).GetString(raw); } catch { return Encoding.UTF8.GetString(raw); } } public static List Read(string path, out string err) { err = ""; List list = new List(); try { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { long len = fs.Length; if (len < 22) { err = "这个文件太小,不像是 zip。"; return list; } int tail = (int)Math.Min(len, 65557); byte[] buf = new byte[tail]; fs.Seek(len - tail, SeekOrigin.Begin); ReadFull(fs, buf, 0, tail); int pos = -1; for (int i = tail - 22; i >= 0; i--) { if (U32(buf, i) != 0x06054b50u) continue; int cl = U16(buf, i + 20); if (i + 22 + cl == tail) { pos = i; break; } } if (pos < 0) { err = "没找到 zip 目录结构,可能不是 zip 文件,或者下载不完整。"; return list; } long cdSize = U32(buf, pos + 12); long cdOffset = U32(buf, pos + 16); int total = U16(buf, pos + 10); if (total == 0xFFFF || cdSize == 0xFFFFFFFFL || cdOffset == 0xFFFFFFFFL) { int loc = pos - 20; if (loc >= 0 && U32(buf, loc) == 0x07064b50u) { long z64Off = (long)U64(buf, loc + 8); if (z64Off >= 0 && z64Off + 56 <= len) { byte[] zb = new byte[56]; fs.Seek(z64Off, SeekOrigin.Begin); ReadFull(fs, zb, 0, 56); if (U32(zb, 0) == 0x06064b50u) { total = (int)Math.Min((long)0x7FFFFFFF, (long)U64(zb, 32)); cdSize = (long)U64(zb, 40); cdOffset = (long)U64(zb, 48); } } } } if (cdOffset < 0 || cdSize < 0 || cdSize > 512L * 1024 * 1024) { err = "zip 目录结构异常,拒绝解析。"; return list; } if (cdOffset + cdSize > len) { err = "zip 目录超出文件末尾,文件可能损坏。"; return list; } byte[] cd = new byte[cdSize]; fs.Seek(cdOffset, SeekOrigin.Begin); ReadFull(fs, cd, 0, (int)cdSize); int p = 0; while (p + 46 <= cd.Length) { if (U32(cd, p) != 0x02014b50u) break; int flags = U16(cd, p + 8); int method = U16(cd, p + 10); ushort tm = U16(cd, p + 12); ushort dt = U16(cd, p + 14); uint crc = U32(cd, p + 16); long comp = U32(cd, p + 20); long uncomp = U32(cd, p + 24); int nl = U16(cd, p + 28); int el = U16(cd, p + 30); int cl = U16(cd, p + 32); int extAttr = (int)U32(cd, p + 38); long off = U32(cd, p + 42); if (p + 46 + nl + el + cl > cd.Length) break; byte[] nameRaw = new byte[nl]; Array.Copy(cd, p + 46, nameRaw, 0, nl); // zip64 扩展字段:按 uncomp / comp / offset 的顺序补 int q = p + 46 + nl; int extraEnd = q + el; while (q + 4 <= extraEnd) { int id = U16(cd, q); int sz = U16(cd, q + 2); if (q + 4 + sz > extraEnd) break; if (id == 0x0001) { int r = q + 4, stop = q + 4 + sz; if (uncomp == 0xFFFFFFFFL && r + 8 <= stop) { uncomp = (long)U64(cd, r); r += 8; } if (comp == 0xFFFFFFFFL && r + 8 <= stop) { comp = (long)U64(cd, r); r += 8; } if (off == 0xFFFFFFFFL && r + 8 <= stop) { off = (long)U64(cd, r); r += 8; } } q += 4 + sz; } ZipItem it = new ZipItem(); it.Name = DecodeName(nameRaw, flags).Replace('\\', '/'); it.Flags = flags; it.Method = method; it.Crc = crc; it.Size = uncomp; it.Packed = comp; it.DosTime = tm; it.DosDate = dt; it.LocalOffset = off; it.IsDir = it.Name.EndsWith("/") || (extAttr & 0x10) != 0; if (it.Name.Length > 0) list.Add(it); p += 46 + nl + el + cl; } } } catch (Exception ex) { err = "读 zip 出错:" + ex.Message; } return list; } static void ReadFull(Stream s, byte[] b, int off, int len) { int got = 0; while (got < len) { int n = s.Read(b, off + got, len - got); if (n <= 0) throw new IOException("文件提前结束"); got += n; } } // 解压到目录。返回成功文件数,失败/跳过写在 skipped 里 public static int ExtractAll(string zipPath, string destDir, bool skipExisting, out string err, out int skipped, Action onItem) { err = ""; skipped = 0; int ok = 0; List items = Read(zipPath, out err); if (err.Length > 0) return 0; if (items.Count == 0) { err = "包里没有条目。"; return 0; } List errs = new List(); try { if (!Directory.Exists(destDir)) Directory.CreateDirectory(destDir); using (FileStream fs = new FileStream(zipPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { for (int i = 0; i < items.Count; i++) { ZipItem it = items[i]; if (onItem != null) onItem(i, items.Count, it.Name); string full; if (!ZipOps.SafeJoin(destDir, it.Name, out full)) { skipped++; errs.Add("跳过可疑路径:" + it.Name); continue; } if (it.IsDir) { try { Directory.CreateDirectory(full); } catch { } continue; } if (it.Encrypted) { skipped++; errs.Add("带密码,跳过:" + it.Name); continue; } if (!it.Supported) { skipped++; errs.Add("不支持的压缩方式 " + it.Method + ":" + it.Name); continue; } if (skipExisting && File.Exists(full)) { skipped++; continue; } try { string parent = Path.GetDirectoryName(full); if (!string.IsNullOrEmpty(parent) && !Directory.Exists(parent)) Directory.CreateDirectory(parent); long dataStart = LocalDataStart(fs, it); if (dataStart < 0) { skipped++; errs.Add("本地头损坏:" + it.Name); continue; } SubStream sub = new SubStream(fs, dataStart, it.Packed); using (FileStream outFs = new FileStream(full, FileMode.Create, FileAccess.Write, FileShare.None)) { if (it.Method == 0) { byte[] b = new byte[65536]; long left = it.Packed; while (left > 0) { int n = sub.Read(b, 0, (int)Math.Min(b.Length, left)); if (n <= 0) break; outFs.Write(b, 0, n); left -= n; } } else { using (DeflateStream ds = new DeflateStream(sub, CompressionMode.Decompress, true)) { byte[] b = new byte[65536]; int n; while ((n = ds.Read(b, 0, b.Length)) > 0) outFs.Write(b, 0, n); } } } ApplyTime(full, it.DosDate, it.DosTime); ok++; } catch (Exception ex) { skipped++; errs.Add(it.Name + ":" + ex.Message); } } } } catch (Exception ex) { err = "解压出错:" + ex.Message; } if (errs.Count > 0) { StringBuilder sb = new StringBuilder(); int show = Math.Min(8, errs.Count); for (int i = 0; i < show; i++) sb.AppendLine("· " + errs[i]); if (errs.Count > show) sb.AppendLine("… 另有 " + (errs.Count - show) + " 条"); err = sb.ToString(); } return ok; } static long LocalDataStart(FileStream fs, ZipItem it) { if (it.LocalOffset < 0 || it.LocalOffset + 30 > fs.Length) return -1; byte[] h = new byte[30]; fs.Seek(it.LocalOffset, SeekOrigin.Begin); int got = 0; while (got < 30) { int n = fs.Read(h, got, 30 - got); if (n <= 0) return -1; got += n; } if (U32(h, 0) != 0x04034b50u) return -1; int nl = U16(h, 26); int el = U16(h, 28); long start = it.LocalOffset + 30 + nl + el; if (start > fs.Length) return -1; return start; } public static DateTime DosToTime(ushort date, ushort time) { try { int y = 1980 + ((date >> 9) & 0x7F); int mo = (date >> 5) & 0x0F; int d = date & 0x1F; int h = (time >> 11) & 0x1F; int mi = (time >> 5) & 0x3F; int s = (time & 0x1F) * 2; if (mo < 1 || mo > 12 || d < 1 || d > 31) return DateTime.Now; if (h > 23 || mi > 59 || s > 59) return DateTime.Now; return new DateTime(y, mo, d, h, mi, s); } catch { return DateTime.Now; } } static void ApplyTime(string path, ushort date, ushort time) { try { DateTime t = DosToTime(date, time); if (Math.Abs((DateTime.Now - t).TotalDays) > 2) File.SetLastWriteTime(path, t); } catch { } } } // 只读、限定长度的子流,用来把 deflate 的数据范围圈住 public class SubStream : Stream { Stream _base; long _start; long _len; long _pos; public SubStream(Stream baseStream, long start, long len) { _base = baseStream; _start = start; _len = len < 0 ? 0 : len; } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override long Length { get { return _len; } } public override long Position { get { return _pos; } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { if (_pos >= _len) return 0; long left = _len - _pos; if (count > left) count = (int)left; _base.Seek(_start + _pos, SeekOrigin.Begin); int n = _base.Read(buffer, offset, count); if (n > 0) _pos += n; return n; } public override void Flush() { } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } } // Dispose 不关底层流,方便 DeflateStream 包在 FileStream 上 public class NonClosingStream : Stream { Stream _base; public NonClosingStream(Stream baseStream) { _base = baseStream; } public override bool CanRead { get { return _base.CanRead; } } public override bool CanSeek { get { return _base.CanSeek; } } public override bool CanWrite { get { return _base.CanWrite; } } public override long Length { get { return _base.Length; } } public override long Position { get { return _base.Position; } set { _base.Position = value; } } public override int Read(byte[] buffer, int offset, int count) { return _base.Read(buffer, offset, count); } public override void Flush() { _base.Flush(); } public override long Seek(long offset, SeekOrigin origin) { return _base.Seek(offset, origin); } public override void SetLength(long value) { _base.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { _base.Write(buffer, offset, count); } protected override void Dispose(bool disposing) { } } // ---------- 写 ---------- public static class ZipOps { // 写包时每条的中心目录记录 class CdRec { public byte[] Name; public int Method; public uint Crc; public long Comp; public long Uncomp; public long Offset; public bool IsDir; public ushort Dt; public ushort Tm; } public static bool IsIgnoredName(string name) { if (string.IsNullOrEmpty(name)) return true; return false; } // 路径安全:拒绝 .. 跳出目录、拒绝盘符和 UNC public static bool SafeJoin(string root, string entryName, out string full) { full = ""; if (string.IsNullOrEmpty(entryName)) return false; string n = entryName.Replace('\\', '/').TrimStart('/'); if (n.Length == 0) return false; if (n.IndexOf(':') >= 0) return false; List keep = new List(); string[] segs = n.Split('/'); foreach (string s0 in segs) { string s = s0.Trim(); if (s.Length == 0 || s == ".") continue; if (s == "..") return false; keep.Add(s); } if (keep.Count == 0) return false; string rootFull = Path.GetFullPath(root); string p = rootFull; foreach (string s in keep) p = Path.Combine(p, s); p = Path.GetFullPath(p); string prefix = rootFull.EndsWith(Path.DirectorySeparatorChar.ToString()) ? rootFull : rootFull + Path.DirectorySeparatorChar; if (!p.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return false; full = p; return true; } // 把用户选的文件/文件夹摊平成条目清单(目录保留空目录本身) public static List Collect(List paths, out string err) { err = ""; List items = new List(); HashSet used = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (string raw in paths) { if (string.IsNullOrEmpty(raw)) continue; try { if (Directory.Exists(raw)) { DirectoryInfo di = new DirectoryInfo(raw); string rootName = Unique(used, di.Name + "/"); items.Add(new ZipWriteItem { Source = di.FullName, Name = rootName, IsDir = true, Size = 0 }); Walk(di, rootName, items, used); } else if (File.Exists(raw)) { FileInfo fi = new FileInfo(raw); string nm = Unique(used, fi.Name); items.Add(new ZipWriteItem { Source = fi.FullName, Name = nm, IsDir = false, Size = fi.Length }); } else { err = "找不到:" + raw; } } catch (Exception ex) { err = "收集文件出错:" + ex.Message; } } return items; } static string Unique(HashSet used, string name) { if (used.Add(name)) return name; bool isDir = name.EndsWith("/"); string baseName = isDir ? name.Substring(0, name.Length - 1) : name; string ext = isDir ? "" : Path.GetExtension(baseName); string stem = isDir ? baseName : Path.GetFileNameWithoutExtension(baseName); for (int i = 2; i < 10000; i++) { string cand = stem + " (" + i + ")" + ext + (isDir ? "/" : ""); if (used.Add(cand)) return cand; } return name; } static void Walk(DirectoryInfo dir, string prefix, List items, HashSet used) { DirectoryInfo[] subs; FileInfo[] files; try { subs = dir.GetDirectories(); files = dir.GetFiles(); } catch { return; } foreach (FileInfo f in files) { try { if ((f.Attributes & FileAttributes.ReparsePoint) != 0) continue; string nm = prefix + Unique(used, f.Name); items.Add(new ZipWriteItem { Source = f.FullName, Name = nm, IsDir = false, Size = f.Length }); } catch { } } foreach (DirectoryInfo d in subs) { try { if ((d.Attributes & FileAttributes.ReparsePoint) != 0) continue; string nm = prefix + Unique(used, d.Name + "/"); // Unique 对带 / 的名字返回的名字已经含 / items.Add(new ZipWriteItem { Source = d.FullName, Name = nm, IsDir = true, Size = 0 }); Walk(d, nm, items, used); } catch { } } } static int DosTimeOf(DateTime t) { return ((t.Hour & 0x1F) << 11) | ((t.Minute & 0x3F) << 5) | ((t.Second / 2) & 0x1F); } static int DosDateOf(DateTime t) { int y = t.Year; if (y < 1980) y = 1980; if (y > 2107) y = 2107; return (((y - 1980) & 0x7F) << 9) | ((t.Month & 0x0F) << 5) | (t.Day & 0x1F); } // 打包。onItem(已完成数量, 总数, 当前名字) public static bool Create(string zipPath, List items, CompressionLevel level, out string err, Action onItem) { err = ""; if (items == null || items.Count == 0) { err = "没有要压缩的内容。"; return false; } List recs = new List(); try { string parentDir = Path.GetDirectoryName(Path.GetFullPath(zipPath)); if (!string.IsNullOrEmpty(parentDir) && !Directory.Exists(parentDir)) Directory.CreateDirectory(parentDir); using (FileStream fs = new FileStream(zipPath, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) { byte[] buf = new byte[65536]; for (int idx = 0; idx < items.Count; idx++) { ZipWriteItem w = items[idx]; if (onItem != null) onItem(idx, items.Count, w.Name); byte[] nameBytes = Encoding.UTF8.GetBytes(w.Name); long sizeGuess = w.IsDir ? 0 : w.Size; bool z64 = sizeGuess >= 0xFFFFFFFFL; DateTime mt = DateTime.Now; try { mt = w.IsDir ? Directory.GetLastWriteTime(w.Source) : File.GetLastWriteTime(w.Source); } catch { } ushort tm = (ushort)DosTimeOf(mt); ushort dt = (ushort)DosDateOf(mt); // 小文件压了反而更大(deflate 头开销),直接存 int method = (w.IsDir || sizeGuess < 128 || level == CompressionLevel.NoCompression) ? 0 : 8; long off = fs.Position; // 本地头 ZipReader.W32(fs, 0x04034b50u); ZipReader.W16(fs, z64 ? 45 : 20); ZipReader.W16(fs, 0x800); // UTF-8 名字 ZipReader.W16(fs, method); ZipReader.W16(fs, tm); ZipReader.W16(fs, dt); ZipReader.W32(fs, 0); // crc 占位 ZipReader.W32(fs, z64 ? 0xFFFFFFFFL : 0); ZipReader.W32(fs, z64 ? 0xFFFFFFFFL : 0); ZipReader.W16(fs, nameBytes.Length); ZipReader.W16(fs, z64 ? 20 : 0); fs.Write(nameBytes, 0, nameBytes.Length); if (z64) { ZipReader.W16(fs, 1); ZipReader.W16(fs, 16); ZipReader.W64(fs, 0); ZipReader.W64(fs, 0); } long dataStart = fs.Position; uint crc = 0; long comp = 0, uncomp = 0; if (!w.IsDir) { using (FileStream src = new FileStream(w.Source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { if (method == 0) { int n; while ((n = src.Read(buf, 0, buf.Length)) > 0) { crc = ZipCrc.Update(crc, buf, 0, n); fs.Write(buf, 0, n); uncomp += n; } comp = uncomp; } else { NonClosingStream nc = new NonClosingStream(fs); using (DeflateStream ds = new DeflateStream(nc, level, true)) { int n; while ((n = src.Read(buf, 0, buf.Length)) > 0) { crc = ZipCrc.Update(crc, buf, 0, n); ds.Write(buf, 0, n); uncomp += n; } } comp = fs.Position - dataStart; } } } long endPos = fs.Position; // 回填 crc 与大小 fs.Seek(off + 14, SeekOrigin.Begin); ZipReader.W32(fs, (long)crc); if (z64) { ZipReader.W32(fs, 0xFFFFFFFFL); ZipReader.W32(fs, 0xFFFFFFFFL); fs.Seek(off + 30 + nameBytes.Length + 4, SeekOrigin.Begin); ZipReader.W64(fs, uncomp); ZipReader.W64(fs, comp); } else { ZipReader.W32(fs, comp); ZipReader.W32(fs, uncomp); } fs.Seek(endPos, SeekOrigin.Begin); CdRec r = new CdRec(); r.Name = nameBytes; r.Method = method; r.Crc = crc; r.Comp = comp; r.Uncomp = uncomp; r.Offset = off; r.IsDir = w.IsDir; r.Dt = dt; r.Tm = tm; recs.Add(r); } if (onItem != null) onItem(items.Count, items.Count, ""); long cdStart = fs.Position; foreach (CdRec r in recs) { bool bigSize = r.Uncomp >= 0xFFFFFFFFL || r.Comp >= 0xFFFFFFFFL; bool bigOff = r.Offset >= 0xFFFFFFFFL; bool big = bigSize || bigOff; byte[] extra = BuildExtra(r.Uncomp, r.Comp, r.Offset, bigSize, bigOff); ZipReader.W32(fs, 0x02014b50u); ZipReader.W16(fs, 45); // 生成方版本(4.5 / zip64) ZipReader.W16(fs, big ? 45 : 20); ZipReader.W16(fs, 0x800); ZipReader.W16(fs, r.Method); ZipReader.W16(fs, r.Tm); ZipReader.W16(fs, r.Dt); ZipReader.W32(fs, (long)r.Crc); ZipReader.W32(fs, r.Comp >= 0xFFFFFFFFL ? 0xFFFFFFFFL : r.Comp); ZipReader.W32(fs, r.Uncomp >= 0xFFFFFFFFL ? 0xFFFFFFFFL : r.Uncomp); ZipReader.W16(fs, r.Name.Length); ZipReader.W16(fs, extra.Length); ZipReader.W16(fs, 0); ZipReader.W16(fs, 0); ZipReader.W16(fs, 0); ZipReader.W32(fs, r.IsDir ? 0x10L : 0x20L); ZipReader.W32(fs, r.Offset >= 0xFFFFFFFFL ? 0xFFFFFFFFL : r.Offset); fs.Write(r.Name, 0, r.Name.Length); if (extra.Length > 0) fs.Write(extra, 0, extra.Length); } long cdSize = fs.Position - cdStart; bool needZip64 = recs.Count > 0xFFFF || cdSize >= 0xFFFFFFFFL || cdStart >= 0xFFFFFFFFL; if (needZip64) { long z64Off = fs.Position; ZipReader.W32(fs, 0x06064b50u); ZipReader.W64(fs, 44); ZipReader.W16(fs, 45); ZipReader.W16(fs, 45); ZipReader.W32(fs, 0); ZipReader.W32(fs, 0); ZipReader.W64(fs, recs.Count); ZipReader.W64(fs, recs.Count); ZipReader.W64(fs, cdSize); ZipReader.W64(fs, cdStart); ZipReader.W32(fs, 0x07064b50u); ZipReader.W32(fs, 0); ZipReader.W64(fs, z64Off); ZipReader.W32(fs, 1); } ZipReader.W32(fs, 0x06054b50u); ZipReader.W16(fs, 0); ZipReader.W16(fs, 0); ZipReader.W16(fs, recs.Count > 0xFFFF ? 0xFFFF : recs.Count); ZipReader.W16(fs, recs.Count > 0xFFFF ? 0xFFFF : recs.Count); ZipReader.W32(fs, cdSize >= 0xFFFFFFFFL ? 0xFFFFFFFFL : cdSize); ZipReader.W32(fs, cdStart >= 0xFFFFFFFFL ? 0xFFFFFFFFL : cdStart); ZipReader.W16(fs, 0); } return true; } catch (Exception ex) { err = "压缩出错:" + ex.Message; try { if (File.Exists(zipPath)) File.Delete(zipPath); } catch { } return false; } } static byte[] BuildExtra(long uncomp, long comp, long offset, bool bigSize, bool bigOff) { if (!bigSize && !bigOff) return new byte[0]; MemoryStream ms = new MemoryStream(); if (bigSize) { ZipReader.W64(ms, uncomp); ZipReader.W64(ms, comp); } if (bigOff) { ZipReader.W64(ms, offset); } byte[] body = ms.ToArray(); MemoryStream all = new MemoryStream(); ZipReader.W16(all, 1); ZipReader.W16(all, body.Length); all.Write(body, 0, body.Length); return all.ToArray(); } public static string SizeText(long bytes) { if (bytes < 1024) return bytes + " B"; double k = bytes / 1024.0; if (k < 1024) return k.ToString("0.#") + " KB"; double m = k / 1024.0; if (m < 1024) return m.ToString("0.#") + " MB"; return (m / 1024.0).ToString("0.##") + " GB"; } // 打包时给个默认包名:第一个条目的位置/名字 public static string DefaultZipName(List items) { string baseDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); string name = "打包_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"); if (items != null && items.Count > 0) { try { string src = items[0].Source; string p = items[0].IsDir ? Path.GetDirectoryName(src.TrimEnd('\\', '/')) : Path.GetDirectoryName(src); if (!string.IsNullOrEmpty(p) && Directory.Exists(p)) baseDir = p; string leaf = Path.GetFileName(src.TrimEnd('\\', '/')); if (!string.IsNullOrEmpty(leaf)) name = leaf; } catch { } } return Path.Combine(baseDir, name + ".zip"); } } public class ZipForm : Form { TabControl _tabs; // 压缩页 ListView _packList; Button _addFiles, _addDir, _remove, _clear, _doZip, _pickOut; TextBox _outPath; ComboBox _level; ProgressBar _packBar; Label _packStatus; List _items = new List(); // 解压页 TextBox _zipPath, _destPath; Button _pickZip, _reload, _pickDest, _doUnzip; ListView _entryList; CheckBox _skipExisting; ProgressBar _unBar; Label _unStatus; List _entries = new List(); public ZipForm() { Text = "压缩解压 - 绿色工具箱"; ClientSize = new Size(788, 588); MinimumSize = new Size(804, 626); StartPosition = FormStartPosition.CenterScreen; Font = new Font("Microsoft YaHei UI", 9f); BackColor = Color.White; AllowDrop = true; 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 = "zip 打包与解压,中文文件名不乱码;rar / 7z 请用对应软件。"; hint.ForeColor = Color.FromArgb(110, 110, 110); hint.SetBounds(16, 44, 700, 20); _tabs = new TabControl(); _tabs.SetBounds(16, 72, 756, 500); _tabs.Font = new Font("Microsoft YaHei UI", 9.5f); TabPage p1 = new TabPage("压缩"); p1.BackColor = Color.White; BuildPackPage(p1); TabPage p2 = new TabPage("解压"); p2.BackColor = Color.White; BuildUnpackPage(p2); _tabs.TabPages.Add(p1); _tabs.TabPages.Add(p2); Controls.Add(title); Controls.Add(hint); Controls.Add(_tabs); DragEnter += delegate(object s, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; }; DragDrop += delegate(object s, DragEventArgs e) { string[] files = e.Data.GetData(DataFormats.FileDrop) as string[]; if (files == null || files.Length == 0) return; string first = files[0]; if (files.Length == 1 && File.Exists(first) && string.Equals(Path.GetExtension(first), ".zip", StringComparison.OrdinalIgnoreCase)) { _tabs.SelectedIndex = 1; LoadZip(first); } else { _tabs.SelectedIndex = 0; AddPaths(files); } }; } void BuildPackPage(TabPage p) { Label hint = new Label(); hint.Text = "把要打包的文件或文件夹加进来(也可以直接拖进窗口)。"; hint.ForeColor = Color.FromArgb(110, 110, 110); hint.SetBounds(14, 10, 620, 20); _packList = new ListView(); _packList.View = View.Details; _packList.FullRowSelect = true; _packList.GridLines = false; _packList.SetBounds(14, 36, 714, 254); _packList.Columns.Add("名称", 440); _packList.Columns.Add("类型", 80); _packList.Columns.Add("大小", 100); _packList.AllowDrop = true; _packList.DragEnter += delegate(object s, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; }; _packList.DragDrop += delegate(object s, DragEventArgs e) { string[] files = e.Data.GetData(DataFormats.FileDrop) as string[]; if (files != null) AddPaths(files); }; _addFiles = new Button(); _addFiles.Text = "添加文件…"; _addFiles.SetBounds(14, 300, 100, 30); _addFiles.Click += delegate { AddFilesDialog(); }; _addDir = new Button(); _addDir.Text = "添加文件夹…"; _addDir.SetBounds(120, 300, 110, 30); _addDir.Click += delegate { AddDirDialog(); }; _remove = new Button(); _remove.Text = "移除选中"; _remove.SetBounds(236, 300, 96, 30); _remove.Click += delegate { RemoveSelected(); }; _clear = new Button(); _clear.Text = "清空"; _clear.SetBounds(338, 300, 70, 30); _clear.Click += delegate { _items.Clear(); RefreshPackList(); }; Label lbOut = new Label(); lbOut.Text = "压缩到"; lbOut.SetBounds(14, 346, 60, 22); _outPath = new TextBox(); _outPath.SetBounds(78, 343, 566, 26); _pickOut = new Button(); _pickOut.Text = "浏览…"; _pickOut.SetBounds(652, 342, 76, 28); _pickOut.Click += delegate { PickOut(); }; Label lbLv = new Label(); lbLv.Text = "压缩级别"; lbLv.SetBounds(14, 384, 60, 22); _level = new ComboBox(); _level.DropDownStyle = ComboBoxStyle.DropDownList; _level.SetBounds(78, 381, 180, 26); _level.Items.Add("标准(推荐)"); _level.Items.Add("最快(压得少,速度优先)"); _level.Items.Add("不压缩(只打包,最快)"); _level.SelectedIndex = 0; Label tip = new Label(); tip.Text = "提示:视频、图片、已压缩的包再压基本不会再小,选「不压缩」更快。"; tip.ForeColor = Color.FromArgb(140, 140, 140); tip.SetBounds(272, 384, 456, 22); _packBar = new ProgressBar(); _packBar.SetBounds(14, 420, 714, 16); _packBar.Minimum = 0; _packBar.Maximum = 100; _packStatus = new Label(); _packStatus.SetBounds(14, 442, 520, 24); _packStatus.Text = "待机"; _packStatus.ForeColor = Color.FromArgb(110, 110, 110); _doZip = new Button(); _doZip.Text = "开始压缩"; _doZip.SetBounds(574, 434, 154, 40); _doZip.BackColor = Color.FromArgb(37, 148, 92); _doZip.ForeColor = Color.White; _doZip.FlatStyle = FlatStyle.Flat; _doZip.Font = new Font("Microsoft YaHei UI", 10f, FontStyle.Bold); _doZip.Click += delegate { DoZip(); }; p.Controls.Add(hint); p.Controls.Add(_packList); p.Controls.Add(_addFiles); p.Controls.Add(_addDir); p.Controls.Add(_remove); p.Controls.Add(_clear); p.Controls.Add(lbOut); p.Controls.Add(_outPath); p.Controls.Add(_pickOut); p.Controls.Add(lbLv); p.Controls.Add(_level); p.Controls.Add(tip); p.Controls.Add(_packBar); p.Controls.Add(_packStatus); p.Controls.Add(_doZip); } void BuildUnpackPage(TabPage p) { Label lbZip = new Label(); lbZip.Text = "压缩包"; lbZip.SetBounds(14, 14, 60, 22); _zipPath = new TextBox(); _zipPath.SetBounds(78, 11, 490, 26); _pickZip = new Button(); _pickZip.Text = "选择…"; _pickZip.SetBounds(576, 10, 70, 28); _pickZip.Click += delegate { PickZip(); }; _reload = new Button(); _reload.Text = "查看内容"; _reload.SetBounds(652, 10, 76, 28); _reload.Click += delegate { LoadZip(_zipPath.Text.Trim()); }; _entryList = new ListView(); _entryList.View = View.Details; _entryList.FullRowSelect = true; _entryList.GridLines = false; _entryList.SetBounds(14, 46, 714, 244); _entryList.Columns.Add("名称", 400); _entryList.Columns.Add("原大小", 100); _entryList.Columns.Add("压缩后", 100); _entryList.Columns.Add("类型", 90); Label lbDest = new Label(); lbDest.Text = "解压到"; lbDest.SetBounds(14, 304, 60, 22); _destPath = new TextBox(); _destPath.SetBounds(78, 301, 566, 26); _pickDest = new Button(); _pickDest.Text = "浏览…"; _pickDest.SetBounds(652, 300, 76, 28); _pickDest.Click += delegate { PickDest(); }; _skipExisting = new CheckBox(); _skipExisting.Text = "跳过已存在的文件(不覆盖)"; _skipExisting.Checked = true; _skipExisting.SetBounds(78, 334, 260, 22); _unBar = new ProgressBar(); _unBar.SetBounds(14, 366, 714, 16); _unBar.Minimum = 0; _unBar.Maximum = 100; _unStatus = new Label(); _unStatus.SetBounds(14, 388, 520, 24); _unStatus.Text = "待机"; _unStatus.ForeColor = Color.FromArgb(110, 110, 110); _doUnzip = new Button(); _doUnzip.Text = "开始解压"; _doUnzip.SetBounds(574, 380, 154, 40); _doUnzip.BackColor = Color.FromArgb(37, 148, 92); _doUnzip.ForeColor = Color.White; _doUnzip.FlatStyle = FlatStyle.Flat; _doUnzip.Font = new Font("Microsoft YaHei UI", 10f, FontStyle.Bold); _doUnzip.Click += delegate { DoUnzip(); }; p.Controls.Add(lbZip); p.Controls.Add(_zipPath); p.Controls.Add(_pickZip); p.Controls.Add(_reload); p.Controls.Add(_entryList); p.Controls.Add(lbDest); p.Controls.Add(_destPath); p.Controls.Add(_pickDest); p.Controls.Add(_skipExisting); p.Controls.Add(_unBar); p.Controls.Add(_unStatus); p.Controls.Add(_doUnzip); } // ---------- 压缩页动作 ---------- void AddFilesDialog() { using (OpenFileDialog d = new OpenFileDialog()) { d.Title = "选择要压缩的文件(可多选)"; d.Multiselect = true; if (d.ShowDialog(this) != DialogResult.OK) return; AddPaths(d.FileNames); } } void AddDirDialog() { using (FolderBrowserDialog d = new FolderBrowserDialog()) { d.Description = "选择要压缩的文件夹(连里面的内容一起打包)"; if (d.ShowDialog(this) != DialogResult.OK) return; AddPaths(new string[] { d.SelectedPath }); } } void AddPaths(string[] paths) { string err; List more = ZipOps.Collect(new List(paths), out err); if (err.Length > 0) MessageBox.Show(err, "提示"); if (more.Count == 0) return; // 直接合并到已有清单(重名由 Collect 内部处理不了,这里再兜一层) HashSet used = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (ZipWriteItem it in _items) used.Add(it.Name); foreach (ZipWriteItem it in more) { string nm = it.Name; if (used.Contains(nm)) { bool isDir = nm.EndsWith("/"); string baseName = isDir ? nm.Substring(0, nm.Length - 1) : nm; string ext = isDir ? "" : Path.GetExtension(baseName); string stem = isDir ? baseName : Path.GetFileNameWithoutExtension(baseName); for (int i = 2; i < 1000; i++) { string cand = stem + " (" + i + ")" + ext + (isDir ? "/" : ""); if (!used.Contains(cand)) { nm = cand; break; } } it.Name = nm; } used.Add(nm); _items.Add(it); } RefreshPackList(); if (_outPath.Text.Trim().Length == 0) _outPath.Text = ZipOps.DefaultZipName(_items); } void RemoveSelected() { if (_packList.SelectedItems.Count == 0) return; List kill = new List(); foreach (ListViewItem li in _packList.SelectedItems) { ZipWriteItem it = li.Tag as ZipWriteItem; if (it != null) kill.Add(it); } foreach (ZipWriteItem it in kill) _items.Remove(it); RefreshPackList(); } void RefreshPackList() { _packList.BeginUpdate(); _packList.Items.Clear(); long total = 0; foreach (ZipWriteItem it in _items) { ListViewItem li = new ListViewItem(it.Name); li.SubItems.Add(it.IsDir ? "文件夹" : "文件"); li.SubItems.Add(it.IsDir ? "-" : ZipOps.SizeText(it.Size)); li.Tag = it; _packList.Items.Add(li); if (!it.IsDir) total += it.Size; } _packList.EndUpdate(); int files = 0; foreach (ZipWriteItem it in _items) if (!it.IsDir) files++; _packStatus.Text = _items.Count == 0 ? "待机" : ("共 " + files + " 个文件," + ZipOps.SizeText(total)); } void PickOut() { using (SaveFileDialog d = new SaveFileDialog()) { d.Title = "压缩包保存到"; d.Filter = "zip 压缩包|*.zip"; d.FileName = "打包_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".zip"; if (_outPath.Text.Trim().Length > 0) d.FileName = Path.GetFileName(_outPath.Text.Trim()); if (d.ShowDialog(this) == DialogResult.OK) _outPath.Text = d.FileName; } } void DoZip() { if (_items.Count == 0) { MessageBox.Show("先添加要压缩的文件或文件夹。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } string outPath = _outPath.Text.Trim(); if (outPath.Length == 0) outPath = ZipOps.DefaultZipName(_items); if (!outPath.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) outPath += ".zip"; _outPath.Text = outPath; if (File.Exists(outPath)) { DialogResult r = MessageBox.Show("已经有一个同名文件:\r\n" + outPath + "\r\n\r\n覆盖它吗?", "确认覆盖", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2); if (r != DialogResult.Yes) return; } CompressionLevel lv = CompressionLevel.Optimal; if (_level.SelectedIndex == 1) lv = CompressionLevel.Fastest; else if (_level.SelectedIndex == 2) lv = CompressionLevel.NoCompression; _doZip.Enabled = false; Cursor = Cursors.WaitCursor; _packBar.Value = 0; string err; DateTime t0 = DateTime.Now; bool ok = ZipOps.Create(outPath, _items, lv, out err, delegate(int done, int total, string name) { int pct = total == 0 ? 100 : (int)(done * 100.0 / total); if (pct < 0) pct = 0; if (pct > 100) pct = 100; _packBar.Value = pct; _packStatus.Text = done >= total ? "正在写入目录…" : ("正在压缩 " + name); Application.DoEvents(); }); Cursor = Cursors.Default; _doZip.Enabled = true; if (!ok) { _packStatus.Text = "压缩失败"; MessageBox.Show(err, "没成功", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } long size = 0; try { size = new FileInfo(outPath).Length; } catch { } double secs = (DateTime.Now - t0).TotalSeconds; _packBar.Value = 100; _packStatus.Text = "完成:" + ZipOps.SizeText(size) + ",用时 " + secs.ToString("0.0") + " 秒"; DialogResult open = MessageBox.Show("压缩完成:\r\n" + outPath + "\r\n\r\n体积 " + ZipOps.SizeText(size) + ",用时 " + secs.ToString("0.0") + " 秒。\r\n\r\n要打开所在文件夹看看吗?", "完成", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (open == DialogResult.Yes) ShowInExplorer(outPath); } // ---------- 解压页动作 ---------- void PickZip() { using (OpenFileDialog d = new OpenFileDialog()) { d.Title = "选择 zip 压缩包"; d.Filter = "zip 压缩包|*.zip|所有文件|*.*"; if (d.ShowDialog(this) != DialogResult.OK) return; LoadZip(d.FileName); } } void PickDest() { using (FolderBrowserDialog d = new FolderBrowserDialog()) { d.Description = "解压到哪个文件夹"; if (d.ShowDialog(this) == DialogResult.OK) _destPath.Text = d.SelectedPath; } } void LoadZip(string path) { if (path.Length == 0) return; if (!File.Exists(path)) { MessageBox.Show("找不到这个文件:\r\n" + path, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } _zipPath.Text = path; string err; Cursor = Cursors.WaitCursor; List list = ZipReader.Read(path, out err); Cursor = Cursors.Default; if (err.Length > 0) { MessageBox.Show(err, "读不了这个包", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } _entries = list; _entryList.BeginUpdate(); _entryList.Items.Clear(); long total = 0; int dirs = 0; foreach (ZipItem it in list) { ListViewItem li = new ListViewItem(it.Name); li.SubItems.Add(it.IsDir ? "-" : ZipOps.SizeText(it.Size)); li.SubItems.Add(it.IsDir ? "-" : ZipOps.SizeText(it.Packed)); string kind = "文件"; if (it.IsDir) { kind = "文件夹"; dirs++; } else if (it.Encrypted) kind = "带密码"; else if (!it.Supported) kind = "压缩方式 " + it.Method; li.SubItems.Add(kind); li.Tag = it; _entryList.Items.Add(li); if (!it.IsDir) total += it.Size; } _entryList.EndUpdate(); if (_destPath.Text.Trim().Length == 0) _destPath.Text = DefaultDest(path); _unStatus.Text = "包内有 " + (list.Count - dirs) + " 个文件" + (dirs > 0 ? "、" + dirs + " 个文件夹" : "") + ",原始大小 " + ZipOps.SizeText(total); } static string DefaultDest(string zipPath) { try { string dir = Path.GetDirectoryName(Path.GetFullPath(zipPath)); string name = Path.GetFileNameWithoutExtension(zipPath); string candidate = Path.Combine(dir, name); int i = 2; string baseName = candidate; while (Directory.Exists(candidate) && Directory.GetFileSystemEntries(candidate).Length > 0) { candidate = baseName + "_" + i; i++; if (i > 999) break; } return candidate; } catch { return Path.Combine(Path.GetTempPath(), "解压结果"); } } void DoUnzip() { string zip = _zipPath.Text.Trim(); if (zip.Length == 0 || !File.Exists(zip)) { MessageBox.Show("先选一个 zip 包。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (_entries.Count == 0) LoadZip(zip); if (_entries.Count == 0) return; string dest = _destPath.Text.Trim(); if (dest.Length == 0) { dest = DefaultDest(zip); _destPath.Text = dest; } int enc = 0; foreach (ZipItem it in _entries) if (it.Encrypted) enc++; if (enc > 0) { MessageBox.Show("这个包里有 " + enc + " 个文件带密码,本工具不破解密码,会跳过它们。\r\n\r\n" + "如果包是别人加密发的,请用原软件先解密。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } _doUnzip.Enabled = false; Cursor = Cursors.WaitCursor; _unBar.Value = 0; string err; int skipped; int ok = ZipReader.ExtractAll(zip, dest, _skipExisting.Checked, out err, out skipped, delegate(int done, int total, string name) { int pct = total == 0 ? 100 : (int)(done * 100.0 / total); if (pct < 0) pct = 0; if (pct > 100) pct = 100; _unBar.Value = pct; _unStatus.Text = "正在解压 " + name; Application.DoEvents(); }); Cursor = Cursors.Default; _doUnzip.Enabled = true; _unBar.Value = 100; _unStatus.Text = "完成:解出 " + ok + " 个文件" + (skipped > 0 ? ",跳过 " + skipped + " 项" : ""); if (ok == 0 && err.Length > 0) { MessageBox.Show(err, "没解出来", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } string msg = "解压完成:解出 " + ok + " 个文件" + (skipped > 0 ? ",跳过 " + skipped + " 项" : "") + "。\r\n\r\n位置:\r\n" + dest; if (err.Length > 0) msg += "\r\n\r\n有几项没处理:\r\n" + err; DialogResult r = MessageBox.Show(msg + "\r\n\r\n打开文件夹看看?", "完成", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (r == DialogResult.Yes) ShowInExplorer(dest); } static void ShowInExplorer(string path) { try { if (Directory.Exists(path)) System.Diagnostics.Process.Start("explorer.exe", "\"" + path + "\""); else if (File.Exists(path)) System.Diagnostics.Process.Start("explorer.exe", "/select,\"" + path + "\""); } catch { } } } // ---------- 自测 ---------- public static class ZipSelfTest { 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-zip") : dir; try { if (Directory.Exists(root)) Directory.Delete(root, true); Directory.CreateDirectory(root); // 1. CRC32 标准检查值 byte[] abc = Encoding.ASCII.GetBytes("123456789"); Check("CRC32(\"123456789\")", ZipCrc.Update(0, abc, 0, abc.Length).ToString("X8"), "CBF43926"); // 2. 造数据 string sub = Path.Combine(root, "素材"); Directory.CreateDirectory(sub); Directory.CreateDirectory(Path.Combine(sub, "子目录")); File.WriteAllText(Path.Combine(sub, "中文名 带空格.txt"), "你好,世界!", new UTF8Encoding(false)); File.WriteAllBytes(Path.Combine(sub, "空文件.bin"), new byte[0]); string bigTxt = Path.Combine(root, "重复内容.txt"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 2000; i++) sb.Append("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\n"); File.WriteAllText(bigTxt, sb.ToString(), new UTF8Encoding(false)); string emptyDir = Path.Combine(root, "空目录"); Directory.CreateDirectory(emptyDir); File.SetLastWriteTime(bigTxt, new DateTime(2020, 3, 4, 5, 6, 6)); string err; List paths = new List(); paths.Add(sub); paths.Add(bigTxt); paths.Add(emptyDir); List items = ZipOps.Collect(paths, out err); Check("收集条目数(素材/ + 子目录/ + 2 文件 + 重复内容 + 空目录/)", items.Count, 6); string zip = Path.Combine(root, "测试包.zip"); bool ok = ZipOps.Create(zip, items, CompressionLevel.Optimal, out err, null); Check("打包成功", ok, true); Check("打包无错误", err, ""); long zipSize = File.Exists(zip) ? new FileInfo(zip).Length : -1; Check("包已生成", zipSize > 0, true); // 3. 读回 string rerr; List back = ZipReader.Read(zip, out rerr); Check("读回无错误", rerr, ""); Check("读回条目数", back.Count, 6); Check("中文名不乱码", HasName(back, "素材/中文名 带空格.txt"), true); Check("路径用正斜杠", HasName(back, "素材/子目录/"), true); Check("空目录条目在", HasName(back, "空目录/"), true); Check("空目录被识别为目录", IsDir(back, "空目录/"), true); long packedBig = -1, sizeBig = -1, methodBig = -1; foreach (ZipItem it in back) { if (it.Name == "重复内容.txt") { packedBig = it.Packed; sizeBig = it.Size; methodBig = it.Method; } } Check("大文本用 deflate", methodBig, 8); Check("重复内容被压小(< 1/5)", packedBig > 0 && packedBig < sizeBig / 5, true); // 4. 解压 string dest = Path.Combine(root, "解出"); string exErr; int skipped; int n = ZipReader.ExtractAll(zip, dest, false, out exErr, out skipped, null); Check("解出文件数(3 个文件,目录不算)", n, 3); Check("解压无错误", exErr, ""); Check("跳过 0 项", skipped, 0); string destTxt = Path.Combine(dest, "素材", "中文名 带空格.txt"); Check("中文文件解出来了", File.Exists(destTxt), true); Check("内容一致", File.Exists(destTxt) ? File.ReadAllText(destTxt, Encoding.UTF8) : "", "你好,世界!"); Check("空文件解出来了", File.Exists(Path.Combine(dest, "素材", "空文件.bin")), true); long zeroLen = -1; try { zeroLen = new FileInfo(Path.Combine(dest, "素材", "空文件.bin")).Length; } catch { } Check("空文件长度 0", zeroLen, 0); Check("空目录也建了", Directory.Exists(Path.Combine(dest, "空目录")), true); Check("大文本内容一致", SameText(Path.Combine(dest, "重复内容.txt"), bigTxt), true); DateTime t = DateTime.MinValue; try { t = File.GetLastWriteTime(Path.Combine(dest, "重复内容.txt")); } catch { } Check("修改时间还原(2020-03-04 05:06:06)", t.ToString("yyyy-MM-dd HH:mm:ss"), "2020-03-04 05:06:06"); // 5. 跳过已存在 File.WriteAllText(destTxt, "我改过了", new UTF8Encoding(false)); int n2 = ZipReader.ExtractAll(zip, dest, true, out exErr, out skipped, null); Check("跳过模式下不覆盖", File.ReadAllText(destTxt, Encoding.UTF8), "我改过了"); Check("跳过模式全命中已存在 → 解出 0", n2, 0); Check("跳过项计数 > 0", skipped > 0, true); int n3 = ZipReader.ExtractAll(zip, dest, false, out exErr, out skipped, null); Check("覆盖模式恢复内容", File.ReadAllText(destTxt, Encoding.UTF8), "你好,世界!"); Check("覆盖模式解出 3 个", n3, 3); // 6. 路径安全 string full; Check("拒绝 ../ 逃逸", ZipOps.SafeJoin(dest, "../evil.txt", out full), false); Check("拒绝嵌套逃逸", ZipOps.SafeJoin(dest, "a/../../evil.txt", out full), false); Check("拒绝盘符", ZipOps.SafeJoin(dest, "C:/Windows/x.txt", out full), false); Check("绝对路径被收进目标目录", ZipOps.SafeJoin(dest, "/etc/passwd", out full), true); Check("绝对路径落在目标下", full.StartsWith(Path.GetFullPath(dest), StringComparison.OrdinalIgnoreCase), true); Check("正常相对路径", ZipOps.SafeJoin(dest, "a/b/c.txt", out full), true); // 7. GBK 老包(通用标志位 0,名字是 GBK 字节) string gbkZip = Path.Combine(root, "老包.zip"); MakeGbkZip(gbkZip, "老照片\\2020 春节.jpg", Encoding.UTF8.GetBytes("JPEGDATA")); List g = ZipReader.Read(gbkZip, out rerr); Check("GBK 包读回 1 条", g.Count, 1); Check("GBK 名字还原", g.Count > 0 ? g[0].Name : "", "老照片/2020 春节.jpg"); string gdest = Path.Combine(root, "GBK解出"); int gn = ZipReader.ExtractAll(gbkZip, gdest, false, out exErr, out skipped, null); Check("GBK 包解出 1 个", gn, 1); Check("GBK 文件名落地", File.Exists(Path.Combine(gdest, "老照片", "2020 春节.jpg")), true); // 8. 不压缩模式 string store = Path.Combine(root, "不压缩.zip"); ZipOps.Create(store, items, CompressionLevel.NoCompression, out err, null); List sBack = ZipReader.Read(store, out rerr); int storeMethod = -1; foreach (ZipItem it in sBack) if (it.Name == "重复内容.txt") storeMethod = it.Method; Check("不压缩模式用 store", storeMethod, 0); Check("不压缩包更大", new FileInfo(store).Length > new FileInfo(zip).Length, true); // 9. 空包拒绝 string emptyErr; bool no = ZipOps.Create(Path.Combine(root, "空.zip"), new List(), CompressionLevel.Optimal, out emptyErr, null); Check("没有内容时拒绝打包", no, false); Check("空包给提示", emptyErr.Length > 0, true); // 10. 重名处理 Directory.CreateDirectory(Path.Combine(root, "重名")); File.WriteAllText(Path.Combine(root, "a.txt"), "1", new UTF8Encoding(false)); File.WriteAllText(Path.Combine(root, "重名", "a.txt"), "2", new UTF8Encoding(false)); List dupPaths = new List(); dupPaths.Add(Path.Combine(root, "a.txt")); dupPaths.Add(Path.Combine(root, "重名", "a.txt")); List dup = ZipOps.Collect(dupPaths, out err); Check("同批重名自动改名", dup.Count == 2 && dup[1].Name == "a (2).txt", true); // 11. 体积文本 Check("SizeText 1536", ZipOps.SizeText(1536), "1.5 KB"); Check("SizeText 0", ZipOps.SizeText(0), "0 B"); // 12. 损坏包 string bad = Path.Combine(root, "坏包.zip"); File.WriteAllBytes(bad, Encoding.ASCII.GetBytes("this is not a zip file at all")); string berr; ZipReader.Read(bad, out berr); Check("非 zip 文件有明确提示", berr.Length > 0, true); } 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-zip.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } static bool HasName(List list, string name) { foreach (ZipItem it in list) if (it.Name == name) return true; return false; } static bool IsDir(List list, string name) { foreach (ZipItem it in list) if (it.Name == name) return it.IsDir; return false; } static bool SameText(string a, string b) { try { return File.ReadAllText(a, Encoding.UTF8) == File.ReadAllText(b, Encoding.UTF8); } catch { return false; } } // 造一个「老工具生成的、GBK 文件名、不置 UTF-8 标志位」的 zip static void MakeGbkZip(string path, string name, byte[] data) { byte[] nb = Encoding.GetEncoding(936).GetBytes(name); uint crc = ZipCrc.Update(0, data, 0, data.Length); ushort dt = (ushort)(((2020 - 1980) << 9) | (1 << 5) | 1); ushort tm = 0; using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write)) { long off = 0; ZipReader.W32(fs, 0x04034b50u); ZipReader.W16(fs, 20); ZipReader.W16(fs, 0); // 关键:flag = 0,没有 UTF-8 位 ZipReader.W16(fs, 0); ZipReader.W16(fs, tm); ZipReader.W16(fs, dt); ZipReader.W32(fs, (long)crc); ZipReader.W32(fs, data.Length); ZipReader.W32(fs, data.Length); ZipReader.W16(fs, nb.Length); ZipReader.W16(fs, 0); fs.Write(nb, 0, nb.Length); fs.Write(data, 0, data.Length); long cd = fs.Position; ZipReader.W32(fs, 0x02014b50u); ZipReader.W16(fs, 20); ZipReader.W16(fs, 20); ZipReader.W16(fs, 0); ZipReader.W16(fs, 0); ZipReader.W16(fs, tm); ZipReader.W16(fs, dt); ZipReader.W32(fs, (long)crc); ZipReader.W32(fs, data.Length); ZipReader.W32(fs, data.Length); ZipReader.W16(fs, nb.Length); ZipReader.W16(fs, 0); ZipReader.W16(fs, 0); ZipReader.W16(fs, 0); ZipReader.W16(fs, 0); ZipReader.W32(fs, 0x20); ZipReader.W32(fs, off); fs.Write(nb, 0, nb.Length); long cdEnd = fs.Position; ZipReader.W32(fs, 0x06054b50u); ZipReader.W16(fs, 0); ZipReader.W16(fs, 0); ZipReader.W16(fs, 1); ZipReader.W16(fs, 1); ZipReader.W32(fs, cdEnd - cd); ZipReader.W32(fs, cd); ZipReader.W16(fs, 0); } } } static class Program { [STAThread] static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(ZipSelfTest.Run(args.Length >= 2 ? args[1] : null)); } // 命令行模式,方便做右键菜单/计划任务: // ziptool.exe --pack out.zip 路径1 路径2... // ziptool.exe --extract in.zip 目标目录 if (args != null && args.Length >= 3 && args[0] == "--pack") { string cerr; List srcs = new List(); for (int i = 2; i < args.Length; i++) srcs.Add(args[i]); List citems = ZipOps.Collect(srcs, out cerr); if (citems.Count == 0) { Environment.Exit(2); return; } bool cok = ZipOps.Create(args[1], citems, CompressionLevel.Optimal, out cerr, null); Environment.Exit(cok ? 0 : 3); return; } if (args != null && args.Length >= 3 && args[0] == "--extract") { string xerr; int xskip; int xn = ZipReader.ExtractAll(args[1], args[2], false, out xerr, out xskip, null); Environment.Exit((xn > 0 || xerr.Length == 0) ? 0 : 4); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new ZipForm()); } } }