欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

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

时间:2021-03-16 10:21:03|栏目:.NET代码|点击:

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

上一篇:Unity UI或3D场景实现跟随手机陀螺仪的晃动效果

栏    目:.NET代码

下一篇:C# 对XML操作入门实例

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

本文地址:http://www.codeinn.net/misctech/81733.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有