ZipHelper.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using UnityEngine;
  2. using System.Collections;
  3. using System;
  4. using System.IO;
  5. using ICSharpCode.SharpZipLib.Checksums;
  6. using ICSharpCode.SharpZipLib.Zip;
  7. namespace cn.sharesdk.unity3d
  8. {
  9. public class ZipHelper
  10. {
  11. public void UnzipWithPath(string path, string dirpath)
  12. {
  13. //这是根目录的路径
  14. string dirPath = dirpath;
  15. //ZipEntry:文件条目 就是该目录下所有的文件列表(也就是所有文件的路径)
  16. ZipEntry zip = null;
  17. //输入的所有的文件流都是存储在这里面的
  18. ZipInputStream zipInStream = null;
  19. //读取文件流到zipInputStream
  20. zipInStream = new ZipInputStream(File.OpenRead(path));
  21. //循环读取Zip目录下的所有文件
  22. while ((zip = zipInStream.GetNextEntry()) != null)
  23. {
  24. UnzipFile(zip, zipInStream, dirPath);
  25. }
  26. try
  27. {
  28. zipInStream.Close();
  29. }
  30. catch (Exception ex)
  31. {
  32. Debug.Log("UnZip Error");
  33. throw ex;
  34. }
  35. }
  36. private void UnzipFile(ZipEntry zip, ZipInputStream zipInStream, string dirPath)
  37. {
  38. try
  39. {
  40. //文件名不为空
  41. if (!string.IsNullOrEmpty(zip.Name))
  42. {
  43. string filePath = dirPath;
  44. filePath += ("/" + zip.Name);
  45. //如果是一个新的文件路径 这里需要创建这个文件路径
  46. if (IsDirectory(filePath))
  47. {
  48. if (!Directory.Exists(filePath))
  49. {
  50. Directory.CreateDirectory(filePath);
  51. }
  52. }
  53. else
  54. {
  55. FileStream fs = null;
  56. //当前文件夹下有该文件 删掉 重新创建
  57. if (File.Exists(filePath))
  58. {
  59. File.Delete(filePath);
  60. }
  61. fs = File.Create(filePath);
  62. int size = 2048;
  63. byte[] data = new byte[2048];
  64. //每次读取2MB 直到把这个内容读完
  65. while (true)
  66. {
  67. size = zipInStream.Read(data, 0, data.Length);
  68. //小于0, 也就读完了当前的流
  69. if (size > 0)
  70. {
  71. fs.Write(data, 0, size);
  72. }
  73. else
  74. {
  75. break;
  76. }
  77. }
  78. fs.Close();
  79. }
  80. }
  81. }
  82. catch (Exception e)
  83. {
  84. Debug.Log("UnZip Error");
  85. throw e;
  86. }
  87. }
  88. private bool IsDirectory(string path)
  89. {
  90. if (path[path.Length - 1] == '/')
  91. {
  92. return true;
  93. }
  94. return false;
  95. }
  96. }
  97. }