C#实现的文件压缩和解压缩类
本文实例讲述了C#实现的文件压缩和解压缩类。分享给大家供大家参考。具体分析如下:
这个C#代码包含了几个类,封装了文件压缩和解压缩常用的方法,包括直接通过代码进行压缩,也有调用winrar对文件进行压缩的
usingSystem; usingSystem.IO; usingSystem.Diagnostics; usingMicrosoft.Win32; usingICSharpCode.SharpZipLib.Checksums; usingICSharpCode.SharpZipLib.Zip; ///压缩、解压缩类 namespaceDotNet.Utilities { publicclassSharpZip { publicSharpZip() {} ///<summary> ///压缩 ///</summary> ///<paramname="filename">压缩后的文件名(包含物理路径)</param> ///<paramname="directory">待压缩的文件夹(包含物理路径)</param> publicstaticvoidPackFiles(stringfilename,stringdirectory) { try { FastZipfz=newFastZip(); fz.CreateEmptyDirectories=true; fz.CreateZip(filename,directory,true,""); fz=null; } catch(Exception) { throw; } } ///<summary> ///解压缩 ///</summary> ///<paramname="file">待解压文件名(包含物理路径)</param> ///<paramname="dir">解压到哪个目录中(包含物理路径)</param> publicstaticboolUnpackFiles(stringfile,stringdir) { try { if(!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } ZipInputStreams=newZipInputStream(File.OpenRead(file)); ZipEntrytheEntry; while((theEntry=s.GetNextEntry())!=null) { stringdirectoryName=Path.GetDirectoryName(theEntry.Name); stringfileName=Path.GetFileName(theEntry.Name); if(directoryName!=String.Empty) { Directory.CreateDirectory(dir+directoryName); } if(fileName!=String.Empty) { FileStreamstreamWriter=File.Create(dir+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; } } streamWriter.Close(); } } s.Close(); returntrue; } catch(Exception) { throw; } } } publicclassClassZip { #region私有方法 ///<summary> ///递归压缩文件夹方法 ///</summary> privatestaticboolZipFileDictory(stringFolderToZip,ZipOutputStreams,stringParentFolderName) { boolres=true; string[]folders,filenames; ZipEntryentry=null; FileStreamfs=null; Crc32crc=newCrc32(); try { entry=newZipEntry(Path.Combine(ParentFolderName,Path.GetFileName(FolderToZip)+"/")); s.PutNextEntry(entry); s.Flush(); filenames=Directory.GetFiles(FolderToZip); foreach(stringfileinfilenames) { fs=File.OpenRead(file); byte[]buffer=newbyte[fs.Length]; fs.Read(buffer,0,buffer.Length); entry=newZipEntry(Path.Combine(ParentFolderName,Path.GetFileName(FolderToZip)+"/"+Path.GetFileName(file))); entry.DateTime=DateTime.Now; entry.Size=fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc=crc.Value; s.PutNextEntry(entry); s.Write(buffer,0,buffer.Length); } } catch { res=false; } finally { if(fs!=null) { fs.Close(); fs=null; } if(entry!=null) { entry=null; } GC.Collect(); GC.Collect(1); } folders=Directory.GetDirectories(FolderToZip); foreach(stringfolderinfolders) { if(!ZipFileDictory(folder,s,Path.Combine(ParentFolderName,Path.GetFileName(FolderToZip)))) { returnfalse; } } returnres; } ///<summary> ///压缩目录 ///</summary> ///<paramname="FolderToZip">待压缩的文件夹,全路径格式</param> ///<paramname="ZipedFile">压缩后的文件名,全路径格式</param> privatestaticboolZipFileDictory(stringFolderToZip,stringZipedFile,intlevel) { boolres; if(!Directory.Exists(FolderToZip)) { returnfalse; } ZipOutputStreams=newZipOutputStream(File.Create(ZipedFile)); s.SetLevel(level); res=ZipFileDictory(FolderToZip,s,""); s.Finish(); s.Close(); returnres; } ///<summary> ///压缩文件 ///</summary> ///<paramname="FileToZip">要进行压缩的文件名</param> ///<paramname="ZipedFile">压缩后生成的压缩文件名</param> privatestaticboolZipFile(stringFileToZip,stringZipedFile,intlevel) { if(!File.Exists(FileToZip)) { thrownewSystem.IO.FileNotFoundException("指定要压缩的文件:"+FileToZip+"不存在!"); } FileStreamZipFile=null; ZipOutputStreamZipStream=null; ZipEntryZipEntry=null; boolres=true; try { ZipFile=File.OpenRead(FileToZip); byte[]buffer=newbyte[ZipFile.Length]; ZipFile.Read(buffer,0,buffer.Length); ZipFile.Close(); ZipFile=File.Create(ZipedFile); ZipStream=newZipOutputStream(ZipFile); ZipEntry=newZipEntry(Path.GetFileName(FileToZip)); ZipStream.PutNextEntry(ZipEntry); ZipStream.SetLevel(level); ZipStream.Write(buffer,0,buffer.Length); } catch { res=false; } finally { if(ZipEntry!=null) { ZipEntry=null; } if(ZipStream!=null) { ZipStream.Finish(); ZipStream.Close(); } if(ZipFile!=null) { ZipFile.Close(); ZipFile=null; } GC.Collect(); GC.Collect(1); } returnres; } #endregion ///<summary> ///压缩 ///</summary> ///<paramname="FileToZip">待压缩的文件目录</param> ///<paramname="ZipedFile">生成的目标文件</param> ///<paramname="level">6</param> publicstaticboolZip(StringFileToZip,StringZipedFile,intlevel) { if(Directory.Exists(FileToZip)) { returnZipFileDictory(FileToZip,ZipedFile,level); } elseif(File.Exists(FileToZip)) { returnZipFile(FileToZip,ZipedFile,level); } else { returnfalse; } } ///<summary> ///解压 ///</summary> ///<paramname="FileToUpZip">待解压的文件</param> ///<paramname="ZipedFolder">解压目标存放目录</param> publicstaticvoidUnZip(stringFileToUpZip,stringZipedFolder) { if(!File.Exists(FileToUpZip)) { return; } if(!Directory.Exists(ZipedFolder)) { Directory.CreateDirectory(ZipedFolder); } ZipInputStreams=null; ZipEntrytheEntry=null; stringfileName; FileStreamstreamWriter=null; try { s=newZipInputStream(File.OpenRead(FileToUpZip)); while((theEntry=s.GetNextEntry())!=null) { if(theEntry.Name!=String.Empty) { fileName=Path.Combine(ZipedFolder,theEntry.Name); if(fileName.EndsWith("/")||fileName.EndsWith("\\")) { Directory.CreateDirectory(fileName); continue; } streamWriter=File.Create(fileName); 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; } } } } } finally { if(streamWriter!=null) { streamWriter.Close(); streamWriter=null; } if(theEntry!=null) { theEntry=null; } if(s!=null) { s.Close(); s=null; } GC.Collect(); GC.Collect(1); } } } publicclassZipHelper { #region私有变量 Stringthe_rar; RegistryKeythe_Reg; Objectthe_Obj; Stringthe_Info; ProcessStartInfothe_StartInfo; Processthe_Process; #endregion ///<summary> ///压缩 ///</summary> ///<paramname="zipname">要解压的文件名</param> ///<paramname="zippath">要压缩的文件目录</param> ///<paramname="dirpath">初始目录</param> publicvoidEnZip(stringzipname,stringzippath,stringdirpath) { try { the_Reg=Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\Shell\Open\Command"); the_Obj=the_Reg.GetValue(""); the_rar=the_Obj.ToString(); the_Reg.Close(); the_rar=the_rar.Substring(1,the_rar.Length-7); the_Info="a"+zipname+""+zippath; the_StartInfo=newProcessStartInfo(); the_StartInfo.FileName=the_rar; the_StartInfo.Arguments=the_Info; the_StartInfo.WindowStyle=ProcessWindowStyle.Hidden; the_StartInfo.WorkingDirectory=dirpath; the_Process=newProcess(); the_Process.StartInfo=the_StartInfo; the_Process.Start(); } catch(Exceptionex) { thrownewException(ex.Message); } } ///<summary> ///解压缩 ///</summary> ///<paramname="zipname">要解压的文件名</param> ///<paramname="zippath">要解压的文件路径</param> publicvoidDeZip(stringzipname,stringzippath) { try { the_Reg=Registry.ClassesRoot.OpenSubKey(@"Applications\WinRar.exe\Shell\Open\Command"); the_Obj=the_Reg.GetValue(""); the_rar=the_Obj.ToString(); the_Reg.Close(); the_rar=the_rar.Substring(1,the_rar.Length-7); the_Info="X"+zipname+""+zippath; the_StartInfo=newProcessStartInfo(); the_StartInfo.FileName=the_rar; the_StartInfo.Arguments=the_Info; the_StartInfo.WindowStyle=ProcessWindowStyle.Hidden; the_Process=newProcess(); the_Process.StartInfo=the_StartInfo; the_Process.Start(); } catch(Exceptionex) { thrownewException(ex.Message); } } } }
希望本文所述对大家的C#程序设计有所帮助。