有些项目为了更好的用户体验,会把下载文件做成一个压缩的文件,直接下载,免得去一个个的点击下载文件。网上有很多压缩文件的方法,也有第三方的分装DLL文件,本文主要介绍DotNetZip压缩方法。

官网下载地址:http://dotnetzip.codeplex.com/ 


解决DotNetZip压缩中文名称乱码,只需要在实例化时设置编码:System.Text.Encoding.Default

即:ZipFile zip = new ZipFile(System.Text.Encoding.Default)。

解决DotNetZip压缩后的文件有多层目录:zip.AddFile(file,"");  

AddFile加上第二个参数即可去掉多层的文件夹。


#region bool SaveFile(string filePath, byte[] bytes) 文件保存,
/// <summary>
/// 文件保存,特别是有些文件放到数据库,可以直接从数据取二进制,然后保存到指定文件夹
/// </summary>
/// <param name="filePath">保存文件地址</param>
/// <param name="bytes">文件二进制</param>
/// <returns></returns>
public static bool SaveFile(string filePath, byte[] bytes)
{
bool result = true;
try
{
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
fileStream.Write(bytes, 0, bytes.Length);
}
}
catch (Exception)
{
result = false;
}
return result;
}
#endregion

#region 判断文件夹是否存在
/// <summary>
/// 判断文件夹是否存在
/// </summary>
/// <param name="path">文件夹地址</param>
/// <returns></returns>
public static bool directoryExist(string path)
{
if (!string.IsNullOrEmpty(path) && Directory.Exists(path))
{
return true;
}
return false;
}
#endregion

#region 创建文件夹
/// <summary>
/// 创建文件夹
/// </summary>
/// <param name="path">文件地址</param>
/// <returns></returns>
public static bool directoryAdd(string path)
{
if (!string.IsNullOrEmpty(path) && !Directory.Exists(path))
{
Directory.CreateDirectory(path); //新建文件夹
return true;
}
return false;
}
#endregion

#region 获取压缩后的文件路径
/// <summary>
/// 获取压缩后的文件路径
/// </summary>
/// <param name="dirPath">压缩的文件路径</param>
/// <param name="filesPath">多个文件路径</param>
/// <returns></returns>
public static string GetCompressPath(string dirPath, List<string> filesPath)
{
var zipPath = "";//返回压缩后的文件路径
using (ZipFile zip = new ZipFile(System.Text.Encoding.Default)) //System.Text.Encoding.Default设置中文附件名称乱码,不设置会出现乱码
{
foreach (var file in filesPath)
{
zip.AddFile(file,"");
//第二个参数为空,说明压缩的文件不会存在多层文件夹。比如C:\test\a\b\c.doc 压缩后解压文件会出现c.doc
//如果改成zip.AddFile(file);则会出现多层文件夹压缩,比如C:\test\a\b\c.doc 压缩后解压文件会出现test\a\b\c.doc
}
zipPath = string.Format("{0}\\{1}.zip", dirPath, DateTime.Now.ToString("yyyyMMddHHmmss"));
zip.Save(zipPath);
}
return zipPath;
}
#endregion


调用:


List<string> filesPath = new List<string>();
filesPath.Add(“C:/test/a.doc”);
filesPath.Add(“C:/test/b.doc”);
//filesPath.Add(Server.MapPath("~/text/Files/c.doc"));//可以设置添加虚拟路径

var dirPath="Server.MapPath("~/compress/")";
var filePath=GetCompressPath(dirPath,filesPath);//返回压缩的文件