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#程序设计有所帮助。