欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现Zip压缩目录中所有文件的方法

程序员文章站 2023-11-20 23:21:10
本文实例讲述了c#实现zip压缩目录中所有文件的方法。分享给大家供大家参考。具体实现方法如下: using system; using system.io;...

本文实例讲述了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#程序设计有所帮助。