将零散文件使用ICSharpCode.SharpZipLib压缩打包后一次性下载
2016-08-31 19:21
691 查看
public static Stream CreateZip(List<string> listPath, int level = 5)
{
MemoryStream mstream = new MemoryStream();
using (ZipOutputStream zipstream = new ZipOutputStream(mstream))
{
zipstream.SetLevel(level);
Crc32 crc = new Crc32();
foreach (var path in listPath)
{
FileStream fs = File.Open(path, FileMode.Open);
//重置流的位置
fs.Position = 0L;
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
//ZIP文件条目
ZipEntry entry = new ZipEntry(Path.GetFileName(path));
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
//冗余校验码
entry.Crc = crc.Value;
zipstream.PutNextEntry(entry);
zipstream.Write(buffer, 0, buffer.Length);
}
//ZipOutputStream关闭后不关闭mstream
zipstream.IsStreamOwner = false;
}
//重置流的位置
mstream.Position = 0L;
return mstream;
}
使用流读取并压缩文件。
在MVC中使用FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName)方法可直接下载。
contentType可使用"application/x-zip-compressed"表示zip文件类型。
{
MemoryStream mstream = new MemoryStream();
using (ZipOutputStream zipstream = new ZipOutputStream(mstream))
{
zipstream.SetLevel(level);
Crc32 crc = new Crc32();
foreach (var path in listPath)
{
FileStream fs = File.Open(path, FileMode.Open);
//重置流的位置
fs.Position = 0L;
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
//ZIP文件条目
ZipEntry entry = new ZipEntry(Path.GetFileName(path));
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
//冗余校验码
entry.Crc = crc.Value;
zipstream.PutNextEntry(entry);
zipstream.Write(buffer, 0, buffer.Length);
}
//ZipOutputStream关闭后不关闭mstream
zipstream.IsStreamOwner = false;
}
//重置流的位置
mstream.Position = 0L;
return mstream;
}
使用流读取并压缩文件。
zipstream.IsStreamOwner = false;必须设置
在MVC中使用FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName)方法可直接下载。
contentType可使用"application/x-zip-compressed"表示zip文件类型。
相关文章推荐
- 将零散文件使用ICSharpCode.SharpZipLib压缩打包后一次性下载
- C#使用ICSharpCode.SharpZipLib压缩后进行web批量下载文件
- C#使用ICSharpCode.SharpZipLib压缩后进行web批量下载文件
- C#使用ICSharpCode.SharpZipLib.dll压缩多个文件
- windows mobile 上文件压缩与解压缩(使用ICSharpCode.SharpZipLib.Zip)
- 使用ICSharpCode.SharpZipLib对文件进行压缩或解压
- windows mobile 上文件压缩与解压缩(使用ICSharpCode.SharpZipLib.Zip)
- C#使用ICSharpCode.SharpZipLib.dll进行文件的压缩与解压功能
- C#使用ICSharpCode.SharpZipLib压缩文件
- C#使用ICSharpCode.SharpZipLib对文件进行压缩
- C#使用ICSharpCode.SharpZipLib压缩文件
- C#使用ICSharpCode.SharpZipLib压缩文件
- 使用ICSharpCode.SharpZipLib进行文件压缩,目前还没实现加密压缩/解压缩。
- C# ICSharpCode.SharpZipLib.dll文件压缩和解压功能类整理,上传文件或下载文件很常用
- .Net 下利用ICSharpCode.SharpZipLib.dll实现文件/文件夹压缩、解压缩(改进)
- 在使用ICSharpCode.SharpZipLib进行目录压缩后,再解压缩是提示这个错误Size mismatch: 4294967295;126976 70202;126976
- ASP.NET生成压缩文件(rar打包)ICSharpCode.SharpZipLib.dll
- 利用ICSharpCode.SharpZipLib对压缩文件添加新文件
- 使用ICSharpCode.SharpZipLib-(C#)实现解压缩文件的操作类
- 在使用ICSharpCode.SharpZipLib进行目录压缩后,再解压缩是提示这个错误Size mismatch: 4294967295;126976 70202;126976