基于ICSharpCode.SharpZipLib组件的打包压缩目录的方法
一、NuGet下载ICSharpCode.SharpZipLib组件
打开NuGet管理器,搜索关键字:ICSharpCode.SharpZipLib,
然后选中安装ICSharpCode.SharpZipLib,这里选择版本为:1.3.3.11
压缩后文件样式:
二、打包压缩下载功能
//下载离线文件功能
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public ResultData downloadBW()
{
ResultData r = new ResultData();
r.Result = false;
//
try
{
string ywxh = WebEnv.Instance.GetContextValue("ywxh");
//
string sql = "select xzdybm from sjsb_sbdata where ywxh='" + ywxh + "'";
string xzdydm = this.getValueBySQL(sql);
//
string dir_ath_file = WebEnv.Instance.dir_ath_file_abs_path();
string xzqdmDirPath = dir_ath_file + "\\" + xzdydm;
string ywDirPath = dir_ath_file + "\\" + xzdydm + "\\" + ywxh;
//生成zip压缩文件ywxh.zip
string rarPathFile = xzqdmDirPath + "\\" + ywxh + ".zip";
//压缩
this.createRAR(ywDirPath, rarPathFile);
//
r.Result = true;
r.Data = xzdydm+ "/" + ywxh + ".zip";
//输出下载文件
/*
FileInfo DownloadFile = new FileInfo(rarPathFile);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = false;
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.UTF8) + ";charset=GB2312");
HttpContext.Current.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
HttpContext.Current.Response.WriteFile(DownloadFile.FullName);
HttpContext.Current.Response.Flush();*/
}
catch (Exception ex)
{
LogUtil.Error(ex.Message, ex);
r.Result = false;
r.Message = ex.Message;
throw ex;
}
return r;
}
private bool createRAR(string ywDirPath, string rarPathFile)
{
if (System.IO.File.Exists(rarPathFile) == true)
{
System.IO.File.Delete(rarPathFile);
}
//
using (ZipOutputStream zs = new ZipOutputStream(File.Create(rarPathFile)))
{
zs.SetLevel(9); //压缩级别0-9
createZipFile(ywDirPath, zs);
zs.Finish();
zs.Close();
}
return true;
}
private void createZipFile(string source,ZipOutputStream zs)
{
Crc32 crc = new Crc32();
string[] files = Directory.GetFileSystemEntries(source);
foreach(var file in files)
{
if(Directory.Exists(file))
{ //如果是文件夹里有文件则递归
this.createZipFile(file, zs);
}
else
{ //如果不是则压缩
using (FileStream fs = File.OpenRead(file))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
//获得当前文件路径的目录+文件名
string tempFileName = file.Replace(source.Substring(0,source.LastIndexOf("\\")), "");// file.Substring(file.LastIndexOf("\\") + 1);
//
ZipEntry entry = new ZipEntry(tempFileName);
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
zs.PutNextEntry(entry);
zs.Write(buffer, 0, buffer.Length);
}
}
}
}