You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
3.2 KiB

  1. using Externals.Compression;
  2. using Externals.Compression.Zip;
  3. using Externals.Compression.Checksums;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Text;
  7. namespace Apewer.Internals
  8. {
  9. internal class ZipUtility
  10. {
  11. /// <summary>压缩字典为 .ZIP 文件。</summary>
  12. /// <param name="files">由文件名和文件内容组成的字典。</param>
  13. public static System.IO.MemoryStream ToZip(Dictionary<string, byte[]> files)
  14. {
  15. var memorystream = new System.IO.MemoryStream();
  16. if (files == null) return memorystream;
  17. var zipstream = new ZipOutputStream(memorystream);
  18. zipstream.SetLevel(1);
  19. foreach (var file in files)
  20. {
  21. var crc = new Crc32();
  22. crc.Reset();
  23. crc.Update(file.Value);
  24. var zipentry = new ZipEntry(file.Key);
  25. zipentry.CompressionMethod = CompressionMethod.Deflated;
  26. //vzipentry.Size = vfile.Value.LongLength;
  27. zipentry.Crc = crc.Value;
  28. zipentry.IsUnicodeText = true;
  29. zipstream.PutNextEntry(zipentry);
  30. zipstream.Write(file.Value, 0, file.Value.Length);
  31. zipstream.CloseEntry();
  32. }
  33. zipstream.IsStreamOwner = false;
  34. zipstream.Finish();
  35. zipstream.Flush();
  36. zipstream.Close();
  37. return memorystream;
  38. }
  39. /// <summary>解压 .ZIP 文件为字典。</summary>
  40. public static Dictionary<string, byte[]> FromZip(byte[] zipdata)
  41. {
  42. var result = new Dictionary<string, byte[]>();
  43. if (zipdata == null) return result;
  44. if (zipdata.LongLength < 1) return result;
  45. var packagememory = new System.IO.MemoryStream(zipdata);
  46. try
  47. {
  48. var zipstream = new ZipInputStream(packagememory);
  49. while (true)
  50. {
  51. var entry = zipstream.GetNextEntry();
  52. if (entry == null) break;
  53. if (entry.IsFile)
  54. {
  55. var cellname = entry.Name;
  56. var celldata = new byte[0];
  57. {
  58. var cellstream = new System.IO.MemoryStream();
  59. while (true)
  60. {
  61. var blockdata = new byte[1024];
  62. var blockread = zipstream.Read(blockdata, 0, 1024);
  63. if (blockread < 1) break;
  64. cellstream.Write(blockdata, 0, blockread);
  65. }
  66. celldata = cellstream.ToArray();
  67. cellstream.Dispose();
  68. }
  69. if (result.ContainsKey(cellname)) result[cellname] = celldata;
  70. else result.Add(cellname, celldata);
  71. }
  72. }
  73. zipstream.Dispose();
  74. }
  75. catch { }
  76. packagememory.Dispose();
  77. return result;
  78. }
  79. }
  80. }