1

我收到了一个IFormFileCollection,我想知道如何将这个集合存档到一个zip/rar/whatever archive文件中,并将这个存档作为stream其他地方存储?我只想通过Stream(s) 在内存中工作,因为稍后我将通过 HTTP 发送它。

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;

    }
}
4

1 回答 1

1

在内存中创建档案并遍历集合,将文件添加到档案中。

返回的流将包含压缩到存档中的文件。

然后,您可以随心所欲地使用流

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;
    }
}
于 2020-01-22T13:05:39.517 回答