.Net使用SharpZip解压缩文件
最近,项目中使用到了上传压缩文件,文件上传到服务器后,肯定要解压,取出其中的文件才能使用,在这里做一个小结,Get这个新技能。
首先在使用NuGet管理程序在项目中添加引用ICSharpCode.SharpZipLib.dll.
在项目公共文件夹中添加SharpZip类。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using ICSharpCode.SharpZipLib.Checksums; 2 using ICSharpCode.SharpZipLib.Zip; 3 using Microsoft.Win32; 4 using System; 5 using System.Collections.Generic; 6 using System.Diagnostics; 7 using System.IO; 8 using System.Linq; 9 using System.Text; 10 using System.Threading.Tasks; 11 12 namespace App.Common.SharpZip 13 { 14 15 public class SharpZip 16 { 17 public SharpZip() { } 18 19 /// <summary> 20 /// 解压缩 21 /// </summary> 22 /// <param name="file">待解压文件名(包含物理路径)</param> 23 /// <param name="dir"> 解压到哪个目录中(包含物理路径)</param> 24 public static bool UnpackFiles(string file, string dir) 25 { 26 try 27 { 28 if (!Directory.Exists(dir)) 29 { 30 Directory.CreateDirectory(dir); 31 } 32 ZipInputStream s = new ZipInputStream(File.OpenRead(file)); 33 ZipEntry theEntry; 34 while ((theEntry = s.GetNextEntry()) != null) 35 { 36 string directoryName = Path.GetDirectoryName(theEntry.Name); 37 string fileName = Path.GetFileName(theEntry.Name); 38 if (directoryName != String.Empty) 39 { 40 Directory.CreateDirectory(dir + directoryName); 41 } 42 if (fileName != String.Empty) 43 { 44 FileStream streamWriter = File.Create(dir + fileName); 45 int size = 2048; 46 byte[] data = new byte[2048]; 47 while (true) 48 { 49 size = s.Read(data, 0, data.Length); 50 if (size > 0) 51 { 52 streamWriter.Write(data, 0, size); 53 } 54 else 55 { 56 break; 57 } 58 } 59 streamWriter.Close(); 60 } 61 } 62 s.Close(); 63 return true; 64 } 65 catch (Exception) 66 { 67 throw; 68 } 69 } 70 } 71 }
接着就可以方便的使用这个新技能了
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /// <summary> 2 /// 解压缩 3 /// </summary> 4 /// <returns></returns> 5 public ActionResult UnPack() 6 { 7 ///..... 8 /// 9 10 11 var fullPath = Request.MapPath("/File/Temp/test.zip"); 12 var unpackPath = Request.MapPath("/File/Temp/"); 13 var unpackResult = SharpZip.UnpackFiles(fullPath, unpackPath); 14 if (unpackResult) 15 { 16 ///...... 17 /// 18 } 19 20 21 ///..... 22 /// 23 return Content("success"); 24 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· 本地部署 DeepSeek:小白也能轻松搞定!
· 如何给本地部署的DeepSeek投喂数据,让他更懂你
· 从 Windows Forms 到微服务的经验教训
· 李飞飞的50美金比肩DeepSeek把CEO忽悠瘸了,倒霉的却是程序员
· 超详细,DeepSeek 接入PyCharm实现AI编程!(支持本地部署DeepSeek及官方Dee