2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C# フォルダの中のファイルをZIP化する .NET6

Last updated at Posted at 2022-10-01

.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

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?