今天刚好解答一个问题
c# - How can I compress a Directory then return the resulting byte array, without physically creating zip file on disk? - Stack Overflow
可以练习黑大写的文章 :
使用 C# 实现资料不落地加密 ZIP 压缩-黑暗执行绪,使用 DotNetZip Library 套件。
这次环境为ASP.NET MVC FileResult跟Byte[],写完发现代码真的很精简,之后小档案压缩情况不用再使用产生档案+删除
方式了
Controller :
using System;using System.Web.Mvc;using System.Collections.Generic;using Ionic.Zip;using System.IO;namespace ZipDemo{ public class HomeController : Controller { [HttpGet] public ActionResult Index() { return View(); } [HttpPost] public FileResult Download() { var bytes = default(byte[]); using (var zip = new ZipFile()) { zip.AddEntry("text.txt", new byte[] {}); zip.AddEntry("text\\text.txt", new byte[] {}); using (var ms = new MemoryStream()) { zip.Save(ms); bytes = ms.ToArray(); } } return File(bytes, System.Net.Mime.MediaTypeNames.Application.Zip); } }}
View :
@{Layout = null;}<!DOCTYPE html><html lang="en"><head><!-- CSS Includes --><link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"></head><body><div class="container"><div class="col-md-6 col-md-offset-3"><h1>Download ZIP</h1>@using (Html.BeginForm("Download","Home")){<input type="submit" class="btn btn-success submit" />}</div></div></body></html>
Online Demo Link ZipDoNet_MemoryStream | C# Online Compiler | .NET Fiddle