Reputation: 9370
I am receiving a IFormFileCollection
and I was wondering how can I archive this collection into a zip/rar/whatever archive
file, and send this archive as a stream
somewhere else to be stored?
I want to work only in memory via Stream
(s) since I will send it over HTTP later on.
class ArchiveService {
public Stream ArchiveFiles(string archiveName, IEnumerable<IFormFile> files) {
using MemoryStream stream = new MemoryStream();
using (System.IO.Compression.ZipArchive archive = ZipFile.Open([in memory!], ZipArchiveMode.Create)) {
foreach (var file in files) {
archive.CreateEntry(file.FileName, CompressionLevel.Fastest);
}
//something like -> archive.CopyTo(stream);
}
return stream;
}
}
Upvotes: 1
Views: 1434
Reputation: 247423
Create an archive in memory and traverse the collection, adding the files to the archive.
The returned stream will contain the files compressed into the archive.
You can then do as you wish with the stream
public class ArchiveService {
public Stream ArchiveFiles(IEnumerable<IFormFile> files) {
MemoryStream stream = new MemoryStream();
using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) {
foreach (IFormFile file in files) {
var entry = archive.CreateEntry(file.FileName, CompressionLevel.Fastest);
using (Stream target = entry.Open()) {
file.CopyTo(target);
}
}
}
stream.Position = 0;
return stream;
}
public async Task<Stream> ArchiveFilesAsync(IEnumerable<IFormFile> files) {
MemoryStream stream = new MemoryStream();
using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) {
foreach (IFormFile file in files) {
var entry = archive.CreateEntry(file.FileName, CompressionLevel.Fastest);
using (Stream target = entry.Open()) {
await file.OpenReadStream().CopyToAsync(target);
}
}
}
stream.Position = 0;
return stream;
}
}
Upvotes: 1