今天为了解决压缩分散的文件时,发现想通过压缩对象直接进行文件夹整理很麻烦,因为SharpZipLib没有提供压缩进某个指定文件夹的功能,在反复分析了SharpZipLib提供的各个接口方法后,终于找到了解决方法,现在贴出来,给需要的同学参考参考。
下面是封装的压缩类:
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.IO;
namespace test
{
public class Zip
{
public static ZipOutputStream CreateZip(string targeFile)
{
Directory.CreateDirectory(Path.GetDirectoryName(targeFile));
var s = new ZipOutputStream(File.Create(targeFile));
s.SetLevel(6);
return s;
}
public static void CloseZip(ZipOutputStream zip)
{
zip.Finish();
zip.Close();
}
public static void Compress(ZipOutputStream s, string source, string folder)
{
using (FileStream fs = File.OpenRead(source))
{
var path = string.IsNullOrWhiteSpace(folder) ? source : folder;
byte[] buffer = new byte[4 * 1024];
ZipEntry entry = new ZipEntry(path.Replace(Path.GetPathRoot(path), "") + "\\" + Path.GetFileName(source)); //此处去掉盘符,如D:\123\1.txt 去掉D:
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
}
}
测试方法:
public ActionResult Index()
{
var zip = Zip.CreateZip(@"D:\\testZip\\test.zip");
Zip.Compress(zip, "E:\\Document\\down.png", "");
Zip.Compress(zip, "E:\\Document\\ending.mp4", "D:\\testChildFolder");
zip.Close();
}
原文:http://www.cnblogs.com/foren/p/6244454.html