iT邦幫忙

5

【C#】DotNetZip-Memory FileResult

c#
  • 分享至 

  • xImage
  •  

今天剛好解答一個問題
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[],寫完發現代碼真的很精簡,之後小檔案壓縮情況不用再使用產生檔案+刪除方式了 /images/emoticon/emoticon12.gif

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


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言