解压压缩文件

首先添加ICSharpCode.SharpZipLib.dll类库引用

 

实现解压文件代码

 1         /// <summary>
 2         /// 解压压缩文件
 3         /// </summary>
 4         /// <param name="filePath">带物理路径的压缩文件名</param>
 5         /// <param name="dirPath">解压到的目标路径</param>
 6         private  void Unzip(string filePath,string dirPath)
 7         {
 8             if(!Directory.Exists(dirPath))
 9             {
10                 //创建保存目录
11                 Directory.CreateDirectory(dirPath);
12             }
13             ZipInputStream stream = new ZipInputStream(File.OpenRead(filePath));
14             ZipEntry entry;
15             while((entry=stream.GetNextEntry())!=null)
16             {
17 
18                 var dirName= Path.GetDirectoryName(entry.Name);//返回指定路径字符串的目录信息
19                 var filename = Path.GetFileName(entry.Name);//返回指定路径字符串的文件名称
20 
21                 //存在目录信息
22                 if (!string.IsNullOrEmpty(dirName))
23                 {
24                     //创建文件目录
25                     Directory.CreateDirectory(dirPath+dirName);
26                 }
27 
28                 //存在文件
29                 if(!string.IsNullOrEmpty(filename))
30                 {
31                     FileStream filestream = new FileStream(dirPath + entry.Name, FileMode.CreateNew);
32 
33                     byte[] data = new byte[1024];
34                     int size = 1024;
35 
36                     //循环读取文件内容直到到达流结尾,则返回零跳出循环
37                     while (true)
38                     {
39                         //从流中读取字节块并将该数据写入给定缓冲区中
40                         size = stream.Read(data, 0, data.Length);
41                         if (size > 0)
42                         {
43                             //将字节块写入文件流
44                             filestream.Write(data, 0, data.Length);
45                         }
46                         else
47                         {
48                             //读取完毕
49                             break;
50                         }
51                     }
52                     filestream.Close();
53                 }
54                   
55             }
56             
57             
58 
59         }

 

posted @ 2017-11-06 20:34  YanW_Z  阅读(287)  评论(0)    收藏  举报