ZipHelper.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.IO;
  3. using ICSharpCode.SharpZipLib.Checksum;
  4. using ICSharpCode.SharpZipLib.Zip;
  5. namespace CommonTool
  6. {
  7. public class ZipHelper
  8. {
  9. public static ZipHelper Instance { get; } = new ZipHelper();
  10. /// <summary>
  11. /// 压缩文件
  12. /// </summary>
  13. /// <param name="sourceFilePath"></param>
  14. /// <param name="destinationZipFilePath"></param>
  15. public bool CreateZip(string sourceFilePath, string destinationZipFilePath)
  16. {
  17. if (string.IsNullOrEmpty(sourceFilePath))
  18. return false;
  19. if (sourceFilePath[sourceFilePath.Length - 1] != Path.DirectorySeparatorChar)
  20. sourceFilePath += Path.DirectorySeparatorChar;
  21. if (File.Exists(destinationZipFilePath))
  22. {
  23. try
  24. {
  25. File.Delete(destinationZipFilePath);
  26. }
  27. catch
  28. {
  29. return false;
  30. }
  31. }
  32. if (!File.Exists(sourceFilePath) && !Directory.Exists(sourceFilePath))
  33. return false;
  34. ZipOutputStream zipStream = new ZipOutputStream(File.Create(destinationZipFilePath));
  35. zipStream.SetLevel(6); // 压缩级别 0-9
  36. CreateZipFiles(sourceFilePath, zipStream, sourceFilePath);
  37. zipStream.Finish();
  38. zipStream.Close();
  39. return true;
  40. }
  41. /// <summary>
  42. /// 递归压缩文件
  43. /// </summary>
  44. /// <param name="sourceFilePath">待压缩的文件或文件夹路径</param>
  45. /// <param name="zipStream">打包结果的zip文件路径(类似 D:\WorkSpace\a.zip),全路径包括文件名和.zip扩展名</param>
  46. /// <param name="staticFile"></param>
  47. private void CreateZipFiles(string sourceFilePath, ZipOutputStream zipStream, string staticFile)
  48. {
  49. Crc32 crc = new Crc32();
  50. string[] filesArray = Directory.GetFileSystemEntries(sourceFilePath);
  51. foreach (string file in filesArray)
  52. {
  53. if (Directory.Exists(file)) //如果当前是文件夹,递归
  54. {
  55. CreateZipFiles(file, zipStream, staticFile);
  56. }
  57. else //如果是文件,开始压缩
  58. {
  59. FileStream fileStream = File.OpenRead(file);
  60. byte[] buffer = new byte[fileStream.Length];
  61. fileStream.Read(buffer, 0, buffer.Length);
  62. string tempFile = file.Substring(staticFile.LastIndexOf("\\", StringComparison.Ordinal) + 1);
  63. ZipEntry entry = new ZipEntry(tempFile)
  64. {
  65. DateTime = DateTime.Now,
  66. Size = fileStream.Length
  67. };
  68. fileStream.Close();
  69. crc.Reset();
  70. crc.Update(buffer);
  71. entry.Crc = crc.Value;
  72. zipStream.PutNextEntry(entry);
  73. zipStream.Write(buffer, 0, buffer.Length);
  74. }
  75. }
  76. }
  77. }
  78. }