有些項目為了更好的用戶體驗,會把下載文件做成一個壓縮的文件,直接下載,免得去一個個的點擊下載文件。網上有很多壓縮文件的方法,也有第三方的分裝DLL文件,本文主要介紹DotNetZip壓縮方法。
解決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) 文件保存,
///
/// 文件保存,特別是有些文件放到數據庫,可以直接從數據取二進制,然後保存到指定文件夾
///
///保存文件地址
///文件二進制
/// www.Bkjia.com
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 判斷文件夾是否存在
///
/// 判斷文件夾是否存在
///
///文件夾地址
///
public static bool directoryExist(string path)
{
if (!string.IsNullOrEmpty(path) && Directory.Exists(path))
{
return true;
}
return false;
}
#endregion
#region 創建文件夾
///
/// 創建文件夾
///
///文件地址
///
public static bool directoryAdd(string path)
{
if (!string.IsNullOrEmpty(path) && !Directory.Exists(path))
{
Directory.CreateDirectory(path); //新建文件夾
return true;
}
return false;
}
#endregion
#region 獲取壓縮後的文件路徑
///
/// 獲取壓縮後的文件路徑
///
///壓縮的文件路徑
///多個文件路徑
///
public static string GetCompressPath(string dirPath, List 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: estac.doc 壓縮後解壓文件會出現c.doc
//如果改成zip.AddFile(file);則會出現多層文件夾壓縮,比如C: estac.doc 壓縮後解壓文件會出現testac.doc
}
zipPath = string.Format({0}\{1}.zip, dirPath, DateTime.Now.ToString(yyyyMMddHHmmss));
zip.Save(zipPath);
}
return zipPath;
}
#endregion
List filesPath = new List();
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);//返回壓縮的文件