C# 文件/文件夹压缩解压

2021-06-19 01:11

阅读:391

标签:put   value   默认   引用   crc   indexof   eve   exception   byte   

第一次写,还有点小激动,项目上用到的,做个记录先,哈哈。

需要先引用ICSharpCode.SharpZipLib.dll

技术分享图片技术分享图片
  1 using System;
  2 using System.Data;
  3 using System.Configuration;
  4 using System.Collections.Generic;
  5 using System.IO;
  6 using ICSharpCode.SharpZipLib.Zip;
  7 using ICSharpCode.SharpZipLib.Checksums;
  8 namespace BLL
  9 {
 10     ///   
 11     /// 文件(夹)压缩、解压缩  
 12     ///   
 13     public class FileCompression
 14     {
 15         #region 压缩文件
 16         ///     
 17         /// 压缩文件    
 18         ///     
 19         /// 要打包的文件列表    
 20         /// 目标文件名    
 21         /// 压缩品质级别(0~9)    
 22         /// 是否删除原文件  
 23         public static void CompressFile(List fileNames, string GzipFileName, int CompressionLevel, bool deleteFile)
 24         {
 25             ZipOutputStream s = new ZipOutputStream(File.Create(GzipFileName));
 26             try
 27             {
 28                 s.SetLevel(CompressionLevel);   //0 - store only to 9 - means best compression    
 29                 foreach (FileInfo file in fileNames)
 30                 {
 31                     FileStream fs = null;
 32                     try
 33                     {
 34                         fs = file.Open(FileMode.Open, FileAccess.ReadWrite);
 35                     }
 36                     catch
 37                     { continue; }
 38                     //  方法二,将文件分批读入缓冲区    
 39                     byte[] data = new byte[2048];
 40                     int size = 2048;
 41                     ZipEntry entry = new ZipEntry(Path.GetFileName(file.Name));
 42                     entry.DateTime = (file.CreationTime > file.LastWriteTime ? file.LastWriteTime : file.CreationTime);
 43                     s.PutNextEntry(entry);
 44                     while (true)
 45                     {
 46                         size = fs.Read(data, 0, size);
 47                         if (size 0) break;
 48                         s.Write(data, 0, size);
 49                     }
 50                     fs.Close();
 51                     if (deleteFile)
 52                     {
 53                         file.Delete();
 54                     }
 55                 }
 56             }
 57             finally
 58             {
 59                 s.Finish();
 60                 s.Close();
 61             }
 62         }
 63         ///     
 64         /// 压缩文件夹    
 65         ///     
 66         /// 要打包的文件夹    
 67         /// 目标文件名    
 68         /// 压缩品质级别(0~9)    
 69         /// 是否删除原文件夹  
 70         public static void CompressDirectory(string dirPath, string GzipFileName, int CompressionLevel, bool deleteDir)
 71         {
 72             //压缩文件为空时默认与压缩文件夹同一级目录    
 73             if (GzipFileName == string.Empty)
 74             {
 75                 GzipFileName = dirPath.Substring(dirPath.LastIndexOf("//") + 1);
 76                 GzipFileName = dirPath.Substring(0, dirPath.LastIndexOf("//")) + "//" + GzipFileName + ".zip";
 77             }
 78             //if (Path.GetExtension(GzipFileName) != ".zip")  
 79             //{  
 80             //    GzipFileName = GzipFileName + ".zip";  
 81             //}  
 82             using (ZipOutputStream zipoutputstream = new ZipOutputStream(File.Create(GzipFileName)))
 83             {
 84                 zipoutputstream.SetLevel(CompressionLevel);
 85                 Crc32 crc = new Crc32();
 86                 Dictionarystring, DateTime> fileList = GetAllFies(dirPath);
 87                 foreach (KeyValuePairstring, DateTime> item in fileList)
 88                 {
 89                     FileStream fs = File.OpenRead(item.Key.ToString());
 90                     byte[] buffer = new byte[fs.Length];
 91                     fs.Read(buffer, 0, buffer.Length);
 92                     ZipEntry entry = new ZipEntry(item.Key.Substring(dirPath.Length));
 93                     entry.DateTime = item.Value;
 94                     entry.Size = fs.Length;
 95                     fs.Close();
 96                     crc.Reset();
 97                     crc.Update(buffer);
 98                     entry.Crc = crc.Value;
 99                     zipoutputstream.PutNextEntry(entry);
100                     zipoutputstream.Write(buffer, 0, buffer.Length);
101                 }
102             }
103             if (deleteDir)
104             {
105                 Directory.Delete(dirPath, true);
106             }
107         }
108         ///     
109         /// 获取所有文件    
110         ///     
111         ///     
112         private static Dictionarystring, DateTime> GetAllFies(string dir)
113         {
114             Dictionarystring, DateTime> FilesList = new Dictionarystring, DateTime>();
115             DirectoryInfo fileDire = new DirectoryInfo(dir);
116             if (!fileDire.Exists)
117             {
118                 throw new System.IO.FileNotFoundException("目录:" + fileDire.FullName + "没有找到!");
119             }
120             GetAllDirFiles(fileDire, FilesList);
121             GetAllDirsFiles(fileDire.GetDirectories(), FilesList);
122             return FilesList;
123         }
124         ///     
125         /// 获取一个文件夹下的所有文件夹里的文件    
126         ///     
127         ///     
128         ///     
129         private static void GetAllDirsFiles(DirectoryInfo[] dirs, Dictionarystring, DateTime> filesList)
130         {
131             foreach (DirectoryInfo dir in dirs)
132             {
133                 foreach (FileInfo file in dir.GetFiles("*.*"))
134                 {
135                     filesList.Add(file.FullName, file.LastWriteTime);
136                 }
137                 GetAllDirsFiles(dir.GetDirectories(), filesList);
138             }
139         }
140         ///     
141         /// 获取一个文件夹下的文件    
142         ///     
143         /// 目录名称    
144         /// 文件列表HastTable    
145         private static void GetAllDirFiles(DirectoryInfo dir, Dictionarystring, DateTime> filesList)
146         {
147             foreach (FileInfo file in dir.GetFiles("*.*"))
148             {
149                 filesList.Add(file.FullName, file.LastWriteTime);
150             }
151         }
152         #endregion
153         #region 解压缩文件
154         ///     
155         /// 解压缩文件    
156         ///     
157         /// 压缩包文件名    
158         /// 解压缩目标路径           
159         public static void Decompress(string GzipFile, string targetPath)
160         {
161             //string directoryName = Path.GetDirectoryName(targetPath + "//") + "//";    
162             string directoryName = targetPath;
163             if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);//生成解压目录    
164             string CurrentDirectory = directoryName;
165             byte[] data = new byte[2048];
166             int size = 2048;
167             ZipEntry theEntry = null;
168             using (ZipInputStream s = new ZipInputStream(File.OpenRead(GzipFile)))
169             {
170                 while ((theEntry = s.GetNextEntry()) != null)
171                 {
172                     if (theEntry.IsDirectory)
173                     {// 该结点是目录    
174                         if (!Directory.Exists(CurrentDirectory + theEntry.Name)) Directory.CreateDirectory(CurrentDirectory + theEntry.Name);
175                     }
176                     else
177                     {
178                         if (theEntry.Name != String.Empty)
179                         {
180                             //  检查多级目录是否存在  
181                             if (theEntry.Name.Contains("//"))
182                             {
183                                 string parentDirPath = theEntry.Name.Remove(theEntry.Name.LastIndexOf("//") + 1);
184                                 if (!Directory.Exists(parentDirPath))
185                                 {
186                                     Directory.CreateDirectory(CurrentDirectory + parentDirPath);
187                                 }
188                             }
189 
190                             //解压文件到指定的目录    
191                             using (FileStream streamWriter = File.Create(CurrentDirectory + theEntry.Name))
192                             {
193                                 while (true)
194                                 {
195                                     size = s.Read(data, 0, data.Length);
196                                     if (size 0) break;
197                                     streamWriter.Write(data, 0, size);
198                                 }
199                                 streamWriter.Close();
200                             }
201                         }
202                     }
203                 }
204                 s.Close();
205             }
206         }
207         #endregion
208     }
209 }
View Code

找了好久终于知道怎么把附件放上来了

源代码和dll在附件里面放着o(╥﹏╥)o:

https://files-cdn.cnblogs.com/files/DreamZhao/C%E5%8E%8B%E7%BC%A9%E6%96%87%E4%BB%B6.zip

C# 文件/文件夹压缩解压

标签:put   value   默认   引用   crc   indexof   eve   exception   byte   

原文地址:https://www.cnblogs.com/DreamZhao/p/MrYang.html


评论


亲,登录后才可以留言!