Csharp/C#教程:C#实现Zip压缩目录中所有文件的方法分享

本文实例讲述了C#实现Zip压缩目录中所有文件的方法。分享给大家供大家参考。具体实现方法如下:

usingSystem; usingSystem.IO; usingSystem.Collections; usingSystem.IO.Compression; usingSystem.Collections.Generic; classFolderZip { privateconstlongBUFFER_SIZE=20480; staticvoidmain(string[]args) { stringsourcepath=@"C:tmp"; Queue<FileSystemInfo>Folders=newQueue<FileSystemInfo>(newDirectoryInfo(sourcepath).GetFileSystemInfos()); stringcopytopath=@"D:temp"; copytopath=(copytopath.LastIndexOf(Path.DirectorySeparatorChar)==copytopath.Length-1)?copytopath:copytopath+Path.DirectorySeparatorChar+Path.GetFileName(sourcepath); Directory.CreateDirectory(copytopath); while(Folders.Count>0) { FileSystemInfoatom=Folders.Dequeue(); FileInfosourcefile=atomasFileInfo; if(sourcefile==null) { DirectoryInfodirectory=atomasDirectoryInfo; Directory.CreateDirectory(directory.FullName.Replace(sourcepath,copytopath)); foreach(FileSystemInfonextatomindirectory.GetFileSystemInfos()) Folders.Enqueue(nextatom); } else { stringsourcefilename=sourcefile.FullName; stringzipfilename=sourcefile.FullName.Replace(sourcepath,copytopath)+".zip"; if(!File.Exists(zipfilename)) { FileStreamsourceStream=null; FileStreamdestinationStream=null; GZipStreamcompressedStream=null; try { //Readthebytesfromthesourcefileintoabytearray sourceStream=newFileStream(sourcefilename,FileMode.Open,FileAccess.Read,FileShare.Read); //OpentheFileStreamtowriteto destinationStream=newFileStream(zipfilename,FileMode.OpenOrCreate,FileAccess.Write); //Createacompressionstreampointingtothedestiantionstream compressedStream=newDeflateStream(destinationStream,CompressionMode.Compress,true); longbufferSize=sourceStream.Length<BUFFER_SIZE?sourceStream.Length:BUFFER_SIZE; byte[]buffer=newbyte[bufferSize]; intbytesRead=0; longbytesWritten=0; while((bytesRead=sourceStream.Read(buffer,0,buffer.Length))!=0) { compressedStream.Write(buffer,0,bytesRead); bytesWritten+=bufferSize; } } catch(ApplicationException) { continue; } finally { //Makesureweallwayscloseallstreams if(sourceStream!=null)sourceStream.Close(); if(compressedStream!=null)compressedStream.Close(); if(destinationStream!=null)destinationStream.Close(); } } } } } }

希望本文所述对大家的C#程序设计有所帮助。

您可能感兴趣的文章:C#文件流进行压缩和解压缩的方法C#实现rar压缩与解压缩文件的方法asp.netC#实现解压缩文件的方法C#使用GZipStream解压缩数据文件的方法C#实现的文件压缩和解压缩类c#调用winrar解压缩文件代码分享C#中使用WinRAR实现加密压缩及解压缩文件C#使用iCSharpcode进行文件压缩实现方法Windows系统中C#调用WinRAR来压缩和解压缩文件的方法C#使用DeflateStream解压缩数据文件的方法c#实现metro文件压缩解压示例C#实现文件压缩与解压的方法示例【ZIP格式】

标签: 方法 ip

自己模拟写C++中的String类型实例讲解

深入理解Qt中各种消息框对话框的使用

上述就是C#学习教程:C#实现Zip压缩目录中所有文件的方法分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请点击右边联系管理员删除。

如若转载,请注明出处:https://www.ctvol.com/cdevelopment/906681.html

(0)
上一篇 2021年10月24日
下一篇 2021年10月24日

精彩推荐