Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Create in memory archive

Here a simple example of how to create an “in memory” zip file using c# and .Net Framework.

My real need is to send a mail attachment containing a lot of files stored into an Azure Blob Storage container, without having to write anything on the Web Server file system.

Here the code…

You have to add a reference to:
  • System.IO.Compression
  • System.IO.Compression.FileSystem


        ///
        /// Return a Memory Stream which rapresents the zipped archive
        /// of all Memory Stream passed as parameters
        ///
        /// files">
        ///
        private static MemoryStreamcreateZip(ListMyFileInfo> files)
        {
            using (varmemoryStream = new MemoryStream())
            {
                using (vararchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                {
                    foreach (var file in files)
                    {
                        varentryFile = archive.CreateEntry(file.FileName);
                        using (varentryStream = entryFile.Open())
                        {
                            file.FileContent.Seek(0, SeekOrigin.Begin);
                            file.FileContent.CopyTo(entryStream);
                        }
                    }
                }
                returnmemoryStream;
            }
        }
    

    ///
    /// MyFileInfo class stores the file name and its content
    ///
    class MyFileInfo
    {
        public stringFileName { get; set; }
        public MemoryStreamFileContent { get; set; }
    }


This post first appeared on ZSvipullo, please read the originial post: here

Share the post

Create in memory archive

×

Subscribe to Zsvipullo

Get updates delivered right to your inbox!

Thank you for your subscription

×