title: how to avoid 'System.OutOfMemoryException' Merging large number of PDF files using iTextSharp in asp.net mvc c#
body: <p>I am merging large number of pdf files using iTextSharp in asp.net mvc c#, it works fine for small number of files but when it reaches about (1000) files it breaks on line pdf.AddDocument(reader); and throws  'System.OutOfMemoryException'.
  I am already using PdfCopy and FileStream to better utilize memory which is suggested every where I searched. My code is given below. Please suggest me how to handle this.</p>
  <pre><code>        using (FileStream stream = new FileStream(outMergeFile, FileMode.Create))
          {
              Document document = new Document();
              PdfCopy pdf = new PdfCopy(document, stream);
              PdfReader reader = null;
              PdfReader.unethicalreading = true;
              try
              {
                  document.Open();
                  for (int i = 0; i &lt; fileList.Count; i++)
                  {
                      var fileStr = Request.MapPath(fileList[i].Path)                            
                      reader = new PdfReader(fileStr);
                          
                      pdf.AddDocument(reader);
                      reader.Close();
                  }
              }
              catch (Exception ex)
              {
                  reader.Close();
              }
              finally
              {
                  document.Close();
              }
          }
  </code></pre>