This article is about how to create compressed zip file. In some scenario we have to compress multiple files may be text file or CSV file into one zip file and need to upload or allow user to download, for this type of scenario you can follow this approach and get your works done.
First create one model class like below.
public sealed class ZipAttachmentModel {
public string FileName {
get;
set;
}
public byte[] Content {
get;
set;
}
}
Here I am creating one sample txt file. For your scenario, you can create text or CSV or any other type of file.
private byte[] CreateTextFile() {
byte[] filebyte = null;
using(var ms = new MemoryStream()) {
using(TextWriter tw = new StreamWriter(ms)) {
tw.WriteLine("Text file content");
tw.Flush();
ms.Position = 0;
filebyte = ms.ToArray();
}
}
return filebyte;
}
Above method gives me byte array for text content.
Here I have implemented method to return FileContentResult for zip file.
private FileContentResult CompressToZip(List < ZipAttachmentModel > zipAttachmentModels, string zipFileName) {
FileContentResult fileContentResult = null;
using(var compressedStream = new MemoryStream()) {
using(ZipArchive archive = new ZipArchive(compressedStream, ZipArchiveMode.Update, false)) {
foreach(var attachmentModel in zipAttachmentModels) {
var zipArchiveEntry = archive.CreateEntry(attachmentModel.FileName);
using(var originalFileStream = new MemoryStream(attachmentModel.Content)) {
using(var zipEntryStream = zipArchiveEntry.Open()) {
originalFileStream.CopyTo(zipEntryStream);
}
}
}
}
fileContentResult = new FileContentResult(compressedStream.ToArray(), "application/zip") {
FileDownloadName = zipFileName
};
}
return fileContentResult;
}
You need to pass zip file name and list of attachments. Remember you can fill this model with multiple text files, CSV files.
See the return type of this method is FileContentResult so you can upload this to azure blob or at any file storage. You can also return to API response to allow user to download this file.
Now come to last step.
var zipAttachmentList = new List < ZipAttachmentModel > ();
zipAttachmentList.Add(new ZipAttachmentModel() {
Content = CreateTextFile(),
FileName = "Test.txt"
});
var fileContentResult = CompressToZip(zipAttachmentList, "sample.zip");
Here I have prepared models for just text file to demonstrate but you can add more types like csv, pdf, etc.
The important thing is you need to set Content and FileName as per your required file type and file content.