How To Compress Files To Zip In C#

In this article, we will learn how to compress files to zip in C#

First create ZipAttachmentModel class as below

public sealed class ZipAttachmentModel {
    public string FileName {
        get;
        set;
    }
    public byte[] Content {
        get;
        set;
    }
}

Now creating one sample txt 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;
}

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;
}

Now pass zip file name and list of attachments. And 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.

var zipAttachmentList = new List < ZipAttachmentModel > ();
zipAttachmentList.Add(new ZipAttachmentModel() {
    Content = CreateTextFile(),
        FileName = "Test.txt"
});
var fileContentResult = CompressToZip(zipAttachmentList, "sample.zip");

You need to set Content and FileName as per your required file type and file content.

Hope you understand the article , If you still have any questions or queries then please let me know in the comment section, I’ll respond to you as soon as possible.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories