I have a web services that returns a list of files. Something like this:
public FileModel(){
string FileName {get;set;}
byte[] FileStream {get;set;}
string FileType {get;set;}
}
My Service would return:
List<FileModel> files;
I have to return this list to browser, so I need to compress these files into a zip folder.
However, I cant figure out how to do this, as .NET ZipArchive CreateFromDirectory is requiring me to provide a directory where the file to be zipped are. But I don't have a directory, I just have this list. How can I covert this list to a zipped folder.
Given
public FileModel(){
string FileName {get;set;}
byte[] FileStream {get;set;}
string FileType {get;set;}
}
The following was written to create a zip file
static class FileModelCompression {
public static Stream Compress(this IEnumerable<FileModel> files) {
if (files.Any()) {
var ms = new MemoryStream();
using(var archive = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true)) {
foreach (var file in files) {
var entry = archive.add(file);
}
}// disposal of archive will force data to be written to memory stream.
ms.Position = 0; //reset memory stream position.
return ms;
}
return null;
}
private static ZipArchiveEntry add(this ZipArchive archive, FileModel file) {
var entry = archive.CreateEntry(file.FileName, CompressionLevel.Fastest);
using (var stream = entry.Open()) {
file.FileStream.CopyTo(stream);
}
return entry;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With