手机
当前位置:查字典教程网 >编程开发 >C#教程 >C#实现Zip压缩目录中所有文件的方法
C#实现Zip压缩目录中所有文件的方法
摘要:本文实例讲述了C#实现Zip压缩目录中所有文件的方法。分享给大家供大家参考。具体实现方法如下:usingSystem;usingSystem...

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

using System; using System.IO; using System.Collections; using System.IO.Compression; using System.Collections.Generic; class FolderZip { private const long BUFFER_SIZE = 20480; static void main(string[] args) { string sourcepath=@"C:tmp"; Queue<FileSystemInfo> Folders = new Queue<FileSystemInfo>(new DirectoryInfo(sourcepath).GetFileSystemInfos()); string copytopath = @"D:temp"; copytopath = (copytopath.LastIndexOf(Path.DirectorySeparatorChar) == copytopath.Length - 1) ? copytopath : copytopath+Path.DirectorySeparatorChar + Path.GetFileName(sourcepath); Directory.CreateDirectory(copytopath); while (Folders.Count > 0) { FileSystemInfo atom = Folders.Dequeue(); FileInfo sourcefile = atom as FileInfo; if (sourcefile == null) { DirectoryInfo directory = atom as DirectoryInfo; Directory.CreateDirectory(directory.FullName.Replace(sourcepath,copytopath)); foreach (FileSystemInfo nextatom in directory.GetFileSystemInfos()) Folders.Enqueue(nextatom); } else { string sourcefilename = sourcefile.FullName; string zipfilename = sourcefile.FullName.Replace(sourcepath,copytopath) + ".zip"; if (!File.Exists(zipfilename)) { FileStream sourceStream = null; FileStream destinationStream = null; GZipStream compressedStream = null; try { // Read the bytes from the source file into a byte array sourceStream = new FileStream(sourcefilename, FileMode.Open, FileAccess.Read, FileShare.Read); // Open the FileStream to write to destinationStream = new FileStream(zipfilename, FileMode.OpenOrCreate, FileAccess.Write); // Create a compression stream pointing to the destiantion stream compressedStream = new DeflateStream(destinationStream, CompressionMode.Compress, true); long bufferSize = sourceStream.Length < BUFFER_SIZE ? sourceStream.Length : BUFFER_SIZE; byte[] buffer = new byte[bufferSize]; int bytesRead = 0; long bytesWritten = 0; while ((bytesRead = sourceStream.Read(buffer, 0, buffer.Length)) != 0) { compressedStream.Write(buffer, 0, bytesRead); bytesWritten += bufferSize; } } catch (ApplicationException) { continue; } finally { // Make sure we allways close all streams if (sourceStream != null) sourceStream.Close(); if (compressedStream != null) compressedStream.Close(); if (destinationStream != null) destinationStream.Close(); } } } } } }

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

【C#实现Zip压缩目录中所有文件的方法】相关文章:

C# IP地址与整数之间转换的具体方法

c#之利用API函数实现动画窗体的方法详解

c# 获取数据库中所有表名称的方法

C#实现对AES加密和解密的方法

C#访问应用程序配置文件的方法

c#实现用SQL池,多线程定时批量执行SQL语句的方法

C#图片压缩的实现方法

C#实现图片分割方法与代码

C#获取系统版本信息方法

使用C#实现阿拉伯数字到大写中文的转换

精品推荐
分类导航