当前位置: 移动技术网 > IT编程>开发语言>c# > C#实现Zip压缩目录中所有文件的方法

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网