一、先书写解压压缩包的方法
一共需要两个参数:
-
zipPath 压缩包所在路径
-
filePath 文件解压之后的路径
-
下面这个图是我的压缩包文件
4.解压方法如下:
/// <summary> /// 解压压缩包 /// </summary> /// <param name="zipPath">压缩包路径</param> /// <param name="filePath">解压之后的文件存放路径</param> /// <returns></returns> public static bool UnZipToFile(string zipPath, string filePath) { if (string.IsNullOrEmpty(zipPath) || !System.IO.File.Exists(zipPath)) { Console.WriteLine("压缩文件不存在!"); return false; } //解压文件路径为空时,默认为与压缩包同路径 解压 if (string.IsNullOrEmpty(filePath)) { filePath = zipPath.Replace(Path.GetFileName(zipPath), ""); } //判断解压的文件路径 最后的字符是不是 \\ if (!filePath.EndsWith("\\")) { filePath += "\\"; } //判断解压的文件是否存在 if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } try { using ZipInputStream s = new ZipInputStream(System.IO.File.OpenRead(zipPath)); ZipEntry entry; while ((entry = s.GetNextEntry()) != null) { string directoryName = Path.GetDirectoryName(entry.Name); string fileName = Path.GetFileName(entry.Name); if (directoryName.Length > 0) { //解压之后的文件名称路径拼接 Directory.CreateDirectory(filePath + directoryName); } if (!directoryName.EndsWith("\\")) { directoryName += "\\"; } if (!string.IsNullOrEmpty(fileName)) { using FileStream fs = System.IO.File.Create(filePath + entry.Name); int size = 1024 * 2; byte[] bytes = new byte[size]; while (true) { size = s.Read(bytes, 0, bytes.Length); if (size > 0) { fs.Write(bytes, 0, size); }else { fs.Close(); break; } } } } } catch (Exception ex) { Console.WriteLine("解压文件发生错误: " + ex.Message); return false; } return true; }
二、在接口中调用解压方法
如图所示 返回值为True 并且我的文件也被解压出来了 则代表我的压缩包解压成功了