MemoryStream - Cannot access a closed Stream when merging PDFs
<p>Can you please tell me, what's wrong with my code? I'm using it to merge PDFs, I create a memory stream then output it to PDF. It works fine for me, but some users cannot download file in IE, or get network error in Chrome:</p>

<pre><code>public static MemoryStream MergePdfForms(List&lt;byte[]&gt; files)
    {
        if (files.Count &gt; 1)
        {
            PdfReader pdfFile;
            Document doc;
            PdfWriter pCopy;
            MemoryStream msOutput = new MemoryStream();

            pdfFile = new PdfReader(files[0]);

            doc = new Document();
            pCopy = new PdfSmartCopy(doc, msOutput);

            doc.Open();

            for (int k = 0; k &lt; files.Count; k++)
            {
                pdfFile = new PdfReader(files[k]);
                for (int i = 1; i &lt; pdfFile.NumberOfPages + 1; i++)
                {
                    ((PdfSmartCopy)pCopy).AddPage(pCopy.GetImportedPage(pdfFile, i));
                }
                pCopy.FreeReader(pdfFile);
            }

            pdfFile.Close();
            pCopy.Close();
            doc.Close();

            return msOutput;
        }
        else if (files.Count == 1)
        {
            return new MemoryStream(files[0]);
        }

        return null;
    }
</code></pre>

<p>After debugging, I've noticed that the memory stream msOutput has some errors:</p>

<p><a href="https://i.stack.imgur.com/323EW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/323EW.jpg" alt="enter image description here"></a></p>

<p>What's causing it, and how to avoid it?</p>

<p>Thank you.</p>