Share via


Memory Stream Zip FIles, Cant Access a Closed Stream

Question

Thursday, August 13, 2020 5:22 PM

I'm prototyping a method that will take in a series of JSON models, create each json file and embed them in a zip file, which will be returned back as a memory stream for the controller.  Which will then download the zip file to the client.

The problem im having is that it thinks the stream is closed, and i don't know why.

Can anybody help? (If i Move the ReturnMemoryStream.Position = 0; up one level into the using block it does not fail)

Fails at : ReturnMemoryStream.Position = 0;

Error : Cannot access a closed Stream.

Second Issue if i test the code with this method in the controller it does not download anything, and i get

An unhandled exception occurred while processing the request.

ObjectDisposedException: Cannot access a closed Stream.

System.IO.MemoryStream.Read(byte[] buffer, int offset, int count)

        [HttpGet("v1/ReaJetPocTestZips")]
        public IActionResult ReaJetPocTestZips()
        {
            try
            {
                var result = this._IReaJetPOCImpl.GetReaJetXMLZips();
                return File(result, "application/zip", "Test.zip");
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        public MemoryStream GetReaJetXMLZips(IEnumerable<JsonRequestModel> JsonRequestModels)
        {
            MemoryStream ReturnMemoryStream = new MemoryStream();

            //compressedFileStream.Seek(0, SeekOrigin.Begin);
            using (var zipArchive = new ZipArchive(ReturnMemoryStream, ZipArchiveMode.Create, false))
            {

                //Create a zip entry for each attachment
                var zipEntry = zipArchive.CreateEntry("NewEntry");

                //Get the stream of the attachment
                using (var originalFileStream = GenerateStreamFromString("Marcs Stuff"))
                {
                    using (var zipEntryStream = zipEntry.Open())
                    {
                            //Copy the attachment stream to the zip entry stream
                            originalFileStream.CopyTo(zipEntryStream);
                    }
                }
            }

            ReturnMemoryStream.Position = 0;
            return ReturnMemoryStream;
        }

        public MemoryStream GenerateStreamFromString(string s)
        {
            MemoryStream ReturnMemoryStream = new MemoryStream();
            var writer = new StreamWriter(ReturnMemoryStream);
            writer.Write(s);
            writer.Flush();
            ReturnMemoryStream.Position = 0;
            return ReturnMemoryStream;
        }

as busy as a bricky in beirut

All replies (5)

Monday, August 17, 2020 9:14 AM âś…Answered | 1 vote

Hi Madaxe2,

Where is the error now? Is it still the same error?

The cause of the error may be the Using statement, which closes the stream at the end of the execution of the code block.

If you need to perform certain operations on the stream, you need to put these operations inside the using statement.

Best Regards,

Timon

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact [email protected].


Thursday, August 13, 2020 6:05 PM

I was able to create an empty zip archive like this, i need help adding a test.txt file

        public MemoryStream GetReaJetXMLZips(IEnumerable<JsonRequestModel> JsonRequestModels=null)
        {

            MemoryStream ReturnMemoryStream = new MemoryStream();

            byte[] file1 = Encoding.ASCII.GetBytes("SomeString");


            using (var archive = new ZipArchive(ReturnMemoryStream, ZipArchiveMode.Create, true))
                {
                    var zipArchiveEntry = archive.CreateEntry("file1.txt", CompressionLevel.Fastest);
                    using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(file1, 0, file1.Length);

                }

            return ReturnMemoryStream;
        }

as bust as a bricky in beirut


Thursday, August 13, 2020 6:10 PM | 1 vote

StreamWriter will close the stream it is given when it is cleaned up. If you don't want that then you need to use the overload that leaves it open.

Michael Taylor http://www.michaeltaylorp3.net


Saturday, August 15, 2020 8:31 PM

I'm still struggling with this,

can anybody show me a fix?

Thanks

Madaxe

        private MemoryStream BuildRootZip()
        {
            MemoryStream ReturnMemoryStream = new MemoryStream();

            using (ReturnMemoryStream)
            {
                using (var archive = new ZipArchive(ReturnMemoryStream, ZipArchiveMode.Create, true))
                {

                    int ZipIndex = 1;
                    foreach (XMLMachiningModel XMLMachiningModel in this._XMLMachiningModels)
                    {
                        string ZipFileName = string.Concat("ReaJetXMLPackage_", ZipIndex, ".zip");
                        byte[] ZipFile = this.BuildSubZip(XMLMachiningModel, ZipFileName);

                        var zipArchiveEntry = archive.CreateEntry(ZipFileName, CompressionLevel.Fastest);

                        using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(ZipFile, 0, ZipFile.Length);

                        ZipIndex++;
                    }
                }
                ReturnMemoryStream.Seek(0, SeekOrigin.Begin);
            }
            return ReturnMemoryStream;
        }

        private byte[] BuildSubZip(XMLMachiningModel XMLMachiningModel, string ZipFileName)
        {
            byte[] ReturnBytes;
            using (var ZipMemoryStream = new MemoryStream())
            {
                using (var archive = new ZipArchive(ZipMemoryStream, ZipArchiveMode.Create, true))
                {
                    var zipArchiveEntry = archive.CreateEntry(ZipFileName, CompressionLevel.Fastest);

                    byte[] XMLFile = Encoding.ASCII.GetBytes(XMLParsing.SerializeObject(XMLMachiningModel.ReaJetSideBase));
                    using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(XMLFile, 0, XMLFile.Length);
                }

                ZipMemoryStream.Position = 0;
                ReturnBytes = new byte[ZipMemoryStream.Length];
                ZipMemoryStream.Read(ReturnBytes, 0, ReturnBytes.Length);
            }
            return ReturnBytes;
        }

as bust as a bricky in beirut


Monday, August 17, 2020 9:49 AM

that got it thanks

as bust as a bricky in beirut