.NET6でフォルダをZIP化してダウンロードする
Zip化クラス
フォルダごとZIP化したい場合、ファイル名をfolder/sample.txt
と指定すればOK
ZipArchiveService.cs
using System;
using System.IO.Compression;
namespace SampleSystems.Service
{
public class ZipArchiveService
{
public byte[] ConvertFilesToBytesForZip(string filePath)
{
using (var ms = new MemoryStream())
{
using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
{
string[] files = Directory.Exists(filePath) ? Directory.GetFiles(filePath) : new string[0];
foreach (var path in files)
{
string fileName = Path.GetFileName(path);
using var fs = System.IO.File.OpenRead(path);
byte[] bytes = new byte[fs.Length];
ZipArchiveEntry addEntry = archive.CreateEntry(fileName, CompressionLevel.Fastest);
using (var entryStream = addEntry.Open())
using (var zipStream = new MemoryStream(bytes))
{
zipStream.CopyTo(entryStream);
}
}
}
return ms.ToArray();
}
}
}
}
.NET Core
だとWebClient
でbyte配列に変換できていたが.NET6
では使えなかった
var client = new WebClient();
byte[] bytes = client.DownloadData(filePath);
コントローラー
View
のボタンを通じてController
から呼ぶ
HomeController.cs
public IActionResult ExportZip()
{
try
{
string filePath = _configuration["Uploads"];
var zs = new ZipArchiveService();
byte[] bytes = zs.ConvertFilesToBytesForZip(filePath);
return File(bytes, "application/zip", "Archive.zip");
}
catch (Exception ex)
{
var failed = new ContentResult();
failed.Content = ex.Message + Environment.NewLine + ex.StackTrace;
return failed;
}
}
Reference