//调用
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);
}
}
}