title: ITextSharp - using PdfStamper resulting MemoryStream to close
body: <p>I'm using ITextSharp to split multi-page PDF files into single page files. I also managed to add those single page PDFs to a zip file using MemoryStream. </p>
  
  <p>Now, I need to add password protection to those PDFs using PdfStamper, before adding them into a zip file. But whenever I tried this, an <code>ObjectDisposedException - Cannot access a closed Stream.</code> is being throwed. </p>
  
  <pre><code>Ionic.Zip.ZipFile zipFile = new Ionic.Zip.ZipFile();
  
          int cnt = 0;
          try
          {
              iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(new iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdfPath), new ASCIIEncoding().GetBytes(""));
  
              for (cnt = 1; cnt &lt;= reader.NumberOfPages; cnt++)
              {
                  using (MemoryStream memoryStream = new MemoryStream())
                  {
                      using (iTextSharp.text.Document document = new iTextSharp.text.Document())
                      {
                          iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, memoryStream);
  
                          using (PdfStamper stamper = new PdfStamper(reader, memoryStream))
                          {
                              stamper.SetEncryption(
                                  null,
                                  Encoding.ASCII.GetBytes("password_here"),
                                  PdfWriter.ALLOW_PRINTING,
                                  PdfWriter.ENCRYPTION_AES_128);
                          }
  
                          memoryStreamForZipFile = new MemoryStream(memoryStream.ToArray());
                          memoryStreamForZipFile.Seek(0, SeekOrigin.Begin);
                      }
                  }
              }
  
              zipFile.Save(destinationFolder + "/" + fileName.Replace(".pdf", ".zip"));
  
              reader.Close();
              reader.Dispose();
          }
          catch
          {
          }
          finally
          {
              GC.Collect();
          }
          return cnt - 1;
  </code></pre>
  
  <p><em>I have removed some codes above for clarity.</em> </p>
  
  <p>If I'll remove the PdfStamper "using" block, the code works just fine. I also tried to juggle the position of PdfStamper to see if I used it in the wrong place. </p>
  
  <p>Am I not using <code>using</code> blocks properly? Or I have to fix some code sequence in here?</p>