//调用
string sourcePath = @"F:\zazhi\book\2013-09";
zipfile.CompressDirector(sourcePath, sourcePath + ".zip", 9, 4096);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;
using ICSharpCode.SharpZipLib.Zip;
using System.Diagnostics;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Checksums;
using System.IO.Packaging;
namespace WindowsFormsApplication1
{
public class zipfile
{
#region 8 压缩文件夹
///
/// 压缩文件夹
///
/// 压缩文件夹的路径
/// 生成的zip文件路径
/// 压缩级别 0 - 9 0是存储级别 9是最大压缩
/// 读取文件的缓冲区大小
public static void CompressDirector(string dirPath, string fileName, int level, int bufferSize)
{
byte[] buffer = new byte[bufferSize];
using (ZipOutputStream s = new ZipOutputStream(File.Create(fileName)))
{
s.SetLevel(level);
CompressDirector(dirPath, dirPath, s, buffer);
s.Finish();
s.Close();
}
}
///
/// 压缩文件夹
///
/// 压缩文件夹路径
/// 压缩文件夹内当前要压缩的文件夹路径
///
/// 读取文件的缓冲区大小
private static void CompressDirector(string root, string path, ZipOutputStream s, byte[] buffer)
{
root = root.TrimEnd('\\') + "\";
string[] fileNames = Directory.GetFiles(path);
string[] dirNames = Directory.GetDirectories(path);
string relativePath = path.Replace(root, "");
if (relativePath != "")
{
relativePath = relativePath.Replace("\", "/") + "/";
}
int sourceBytes;
foreach (string file in fileNames)
{
ZipEntry entry = new ZipEntry(relativePath + Path.GetFileName(file));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
foreach (string dirName in dirNames)
{
string relativeDirPath = dirName.Replace(root, "");
ZipEntry entry = new ZipEntry(relativeDirPath.Replace("\", "/") + "/");
s.PutNextEntry(entry);
CompressDirector(root, dirName, s, buffer);
}
}
#endregion
}
}