4.文件夹及文件压缩

//调用

string sourcePath = @"F:\zazhi\book\2013-09";

ZipManager zm = new ZipManager(sourcePath);

zm.ZipFolder(sourcePath + ".zip");

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Packaging;
using System.IO;
namespace WindowsFormsApplication1
{
   public class ZipManager
    {
       public string SourceFolderPath { get; set; }
       //写一个构造函数,用来接收要执行压缩的文件路径
       public ZipManager(string sourceFolderPath)
       {
           SourceFolderPath = sourceFolderPath;
       }
        //创建一个方法ZipFolder,用来执行实际的压缩操作。在这个方法里面创建一个Package的实例。
       public void ZipFolder(string zipFilePath)
       {
           using (Package package=Package.Open(zipFilePath,System.IO.FileMode.Create))
           {
               //创建一个函数ZipDirectory,用来递归遍历所有的子目录和子文件夹
               DirectoryInfo di = new DirectoryInfo(SourceFolderPath);
               ZipDirectory(di, package);
            }
       }

       //创建一个函数ZipDirectory,用来递归遍历所有的子目录和子文件夹
       private void ZipDirectory(DirectoryInfo di,Package package)
       {
           foreach (FileInfo fi in di.GetFiles())
           {
               //对每一个文件,创建一个PackagePart的实例。
               //注意这里面相对路径的生成过程:截取比源路径多出的部分,并且将右斜线替换成左斜线。
               string relativePath = fi.FullName.Replace(SourceFolderPath,string.Empty);
               relativePath = relativePath.Replace("\","/");
               PackagePart part = package.CreatePart(new Uri(relativePath,UriKind.Relative),"");
               using (FileStream fs=fi.OpenRead())
               {
                   CopyStream(fs,part.GetStream());
               }
           }
           foreach (DirectoryInfo subDi in di.GetDirectories())
           {
               ZipDirectory(subDi, package);
           }
       }
        //复制源文件的内容到Package里面,为此需要添加一个CopyStream方法。
       private  void CopyStream(Stream source, Stream target)
       {
           const int bufSize = 0x100000;
           byte[] buf = new byte[bufSize];
           int bytesRead = 0;
           while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
               target.Write(buf, 0, bytesRead);
       }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值