第一个参数:要压缩的文件夹[也可以是文件夹下面的一个文件]
第二个参数:压缩后文件要保存的路径
private static void CreateZipFile(string filesPath, string zipFilePath)
{
if (!Directory.Exists(filesPath))
{
Console.WriteLine("Cannot find directory '{0}'", filesPath);
return;
}
try
{
string[] filenames = Directory.GetFiles(filesPath);
using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))
{
s.SetLevel(9); // 压缩级别 0-9
//s.Password = "123"; //Zip压缩文件密码
byte[] buffer = new byte[4096]; //缓冲区大小
foreach (string file in filenames)
{
ZipEntry 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);
}
}
----------------------------------------------------------------------------------------------
以上代码直接拉过去用法在下面
string Afterpath = HttpContext.Current.Server.MapPath("~/YaSuo/"); //压缩后要保存的目录【当前程序的目录下面的文件夹】
string Beforepath = HttpContext.Current.Server.MapPath("~/Downloader/");//要压缩的目录【当前程序的目录下面的文件夹】
CreateZip(Beforepath, Afterpath + $"{replace(tablename)}ORM.zip");