zoukankan      html  css  js  c++  java
  • 将零散文件使用ICSharpCode.SharpZipLib压缩打包后一次性下载

    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;
    }


    使用流读取并压缩文件。

    zipstream.IsStreamOwner = false;
    必须设置


    在MVC中使用FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName)方法可直接下载。

    contentType可使用"application/x-zip-compressed"表示zip文件类型。

  • 相关阅读:
    python基础-递归
    python基础-三元表达式/列表推导式/生成器表达式
    python基础-生成器
    python基础-迭代器
    python基础-函数
    python基础-文件操作
    Docker(六)安装Red5进行rtmp推流
    Docker(五)安装Fastdfs
    Docker(四)安装Redis
    Docker(三)安装Mysql
  • 原文地址:https://www.cnblogs.com/letnet/p/8525105.html
Copyright © 2011-2022 走看看