Skip to content

Instantly share code, notes, and snippets.

@stogoh
Created January 3, 2024 17:31
Show Gist options
  • Save stogoh/9c038e6f79ed714de65bc83e0b931b9c to your computer and use it in GitHub Desktop.
Save stogoh/9c038e6f79ed714de65bc83e0b931b9c to your computer and use it in GitHub Desktop.
ASP.NET Core In Memory File Download
internal static class DownloadEndpoint
{
public static void MapDownloadEndpoints(this IEndpointRouteBuilder builder)
{
builder
.MapGet("/api/download/{containerId}", DownloadContainer);
}
private static async Task DownloadContainer(
HttpContext context,
Guid containerId)
{
context.Response.ContentType = "application/octet-stream";
context.Response.Headers.Append("Content-Disposition", $"attachment; filename=\"Container-{containerId}.zip\"");
var folderPath = @$"D:\{containerId}";
var files = Directory.GetFiles(folderPath);
var bodyStream = context.Response.BodyWriter.AsStream();
using var archive = new ZipArchive(bodyStream, ZipArchiveMode.Create);
foreach (var file in files)
{
var entry = archive.CreateEntry(Path.GetFileName(file), CompressionLevel.NoCompression);
var entryStream = entry.Open();
var fileStream = File.OpenRead(file);
await fileStream.CopyToAsync(entryStream);
entryStream.Close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment