c# 文件压缩zip或将zip文件解压的方法
1.必须Dll:
ICSharpCode.SharpZipLib.dll。可从Nutget程序包中获取。
2.压缩文件
//////压缩文件成zip /// ///压缩成zip文件的绝对路径 /// 被压缩指定文件的名字 /// /// publicboolCreateZipFile(stringfileZip,stringfileName,stringzipFilePath) { boolisZip=false; if(!Directory.Exists(zipFilePath)) { Logger.Info($"Cannotfinddirectory{zipFilePath}",false,"FileToZip"); returnisZip; } try { string[]filenames=Directory.GetFiles(zipFilePath); using(ZipOutputStreams=newZipOutputStream(File.Create(fileZip))) { s.SetLevel(9);//压缩级别0-9 //s.Password="123";//Zip压缩文件密码 byte[]buffer=newbyte[4096];//缓冲区大小 foreach(stringfileinfilenames.ToList()) { if(file==zipFilePath+fileName)//指定被压缩文件的绝对路径 { ZipEntryentry=newZipEntry(Path.GetFileName(file)); entry.DateTime=DateTime.Now; s.PutNextEntry(entry); using(FileStreamfs=File.OpenRead(file)) { intsourceBytes; do { sourceBytes=fs.Read(buffer,0,buffer.Length); s.Write(buffer,0,sourceBytes); }while(sourceBytes>0); fs.Close(); fs.Dispose(); } break; } } s.Finish(); s.Close(); isZip=true; } } catch(Exceptionex) { Logger.Info($"Exceptionduringprocessing{0}",false,"FileToZip"); } returnisZip; }
3.将zip文件解压
//////解压文件 /// ///压缩文件的绝对路径 publicvoidUnZipFile(stringzipFilePath) { if(!File.Exists(zipFilePath)) { Logger.Info($"Cannotfindfile{zipFilePath}",false,"FileToZip"); return; } using(ZipInputStreams=newZipInputStream(File.OpenRead(zipFilePath))) { ZipEntrytheEntry; while((theEntry=s.GetNextEntry())!=null) { stringdirectoryName=Path.GetDirectoryName(theEntry.Name); stringfileName=Path.GetFileName(theEntry.Name); //createdirectory if(directoryName?.Length>0) { Directory.CreateDirectory(directoryName); } if(!string.IsNullOrEmpty(fileName)) { using(FileStreamstreamWriter=File.Create(theEntry.Name)) { intsize=2048; byte[]data=newbyte[2048]; while(true) { size=s.Read(data,0,data.Length); if(size>0) { streamWriter.Write(data,0,size); } else { break; } } } } } } }
4.其它:其中的Logger是Log4的用法。
以上这篇c#文件压缩zip或将zip文件解压的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。