Search code examples
c#asp.net-mvczipmemorystreamc#-ziparchive

c# - How can I write a file to memorystream, zip three of those memorystreams, and put that into another memorystream?


First, I want to create three files without actually creating a file like memorystream. I want to compress those three files and put them in a memoeystream. It is possible to put a zip file in memoeystream, but like memorystream, can it actually contain three files without creating a file?

Here is my code,

using (MemoryStream ms = new MemoryStream()) {
    using (ZipArchive fileContainer = new ZipArchive(ms, ZipArchiveMode.Create, true)) {
        using(MemoryStream fileMS = new MemoryStream()){ 
        //I want to create file to like memorystream, Not local  
        //file txt1.txt  contain 123456789        
        //file txt2.txt  contain 12345
        //file txt1.txt  contain 6789    
        }            
    }
    return File(ms.ToArray(), System.Net.Mime.MediaTypeNames.Application.Octet, "Result.zip");
}

Solution

  • Worked fine for me

     using (MemoryStream ms = new MemoryStream())
                {
                    using (ZipArchive archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
                    {
                        for (int i = 0; i < 3; i++)
                        {
                            ZipArchiveEntry readmeEntry = archive.CreateEntry($"text{i}.txt");
                            using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
                            {
                                writer.WriteLine("text");
                            }
                        }
    
                    }
                   return File(ms.ToArray(), System.Net.Mime.MediaTypeNames.Application.Octet, "Result.zip");
                }