1.添加NuGet:SharpZipLib
2.上代码:
static void Main(string[] args)
{
//测试使用:数组第一个数据代表,你将要压缩的文件夹目录,第二个代表压缩生成的文件地址
string[] files = { @"C:\Users\TestFolder", @"C:\Users\TestZIPFile.zip" };
try
{
//获取文件夹下的所有文件
string[] filenames = Directory.GetFiles(files[0]);
//创建压缩文件
using (ZipOutputStream s = new ZipOutputStream(File.Create(files[1])))
{
//0-9 9的质量最高
s.SetLevel(9);
byte[] buffer = new byte[4096];
foreach (string file in filenames)
{
//根据文件名称创建zip项
var entry = new ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
s.Finish();
s.Close();
}
}
catch (Exception ex)
{
Console.WriteLine("Exception during processing {0}", ex);
}
}