asp.net实现文件夹及文件压缩,并实现下载(二)
添加引用:ICSharpCode.SharpZipLib.dll
代码:
#region 压缩并下载代码
private void dlZipDir(string strPath, string strFileName)
{
MemoryStream ms = null;
try
{
Response.ContentType = "application/octet-stream";
strFileName = HttpUtility.UrlEncode(strFileName).Replace('+', ' ');
Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName + ".zip");
ms = new MemoryStream();
zos = new ZipOutputStream(ms);
strBaseDir = strPath + "\\";
addZipEntry(strBaseDir);
zos.Finish();
zos.Close();
Response.Clear();
Response.BinaryWrite(ms.ToArray());
Response.End();
}
catch (Exception ex)
{
if (ms != null)
ms.Close();
if (zos != null)
zos.Close();
}
}
private void addZipEntry(string path)
{
Crc32 crc = new Crc32();
FileStream fs = null;
try
{
DirectoryInfo di = new DirectoryInfo(path);
foreach (DirectoryInfo item in di.GetDirectories())
{
addZipEntry(item.FullName);
}
foreach (FileInfo item in di.GetFiles())
{
fs = File.OpenRead(item.FullName);
if (fs.Length != 0)
{
long fileLength = fs.Length;
long pai = 1024 * 1024 * 20;//每20M写一次
long forint = fs.Length / pai + 1;
byte[] buffer = null;
ZipEntry entry = null;
if (fileLength < 104857600)//150 * 1024 * 1024
{
buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string strEntryName = item.FullName.Replace(strBaseDir, "");
entry = new ZipEntry(strEntryName);
zos.PutNextEntry(entry);
zos.Write(buffer, 0, buffer.Length);
}
else //超过150M则会分块处理
{
entry = new ZipEntry(item.FullName.Replace(strBaseDir, ""));
entry.Size = fs.Length;
entry.DateTime = DateTime.Now;
zos.PutNextEntry(entry);
for (long i = 1; i <= forint; i++)
{
if (pai * i < fs.Length)
{
buffer = new byte[pai];
fs.Seek(pai * (i - 1), System.IO.SeekOrigin.Begin);
}
else
{
if (fs.Length < pai)
{
buffer = new byte[fs.Length];
}
else
{
buffer = new byte[fs.Length - pai * (i - 1)];
fs.Seek(pai * (i - 1), System.IO.SeekOrigin.Begin);
}
}
fs.Read(buffer, 0, buffer.Length);
crc.Reset();
crc.Update(buffer);
zos.Write(buffer, 0, buffer.Length);
zos.Flush();
}
}
}
fs.Close();
}
}
catch (Exception ex)
{
if (fs != null)
fs.Close();
}
}
调用
protected void Button1_Click(object sender, EventArgs e)
{
string filePath = Server.MapPath("files");
dlZipDir(filePath, "files");
}
该方法不会在服务器中保存压缩文件
文件若超过150M则会分块压缩文件。虽然能压缩大型的文件,但大型文件过大或者整体的文件过大 ,也会报错,如:引发类型为“System.OutOfMemoryException”的异常。
其解决方案请看asp.net实现文件夹及文件压缩,并实现下载(三)