title: itextsharp not closing files
body: <p>I've got some code for itextsharp merging 2 pdf files. Found it online somewhere. The merging works fine, but it seems that the source files are staying in use after it is all done. What I'd like to do is to delete the first file that i have already merged, which is uploaded via a fileupload, and keep only the merged file. It's definitely the code doing the merging that is causing the file to stay open. I tried to delete the file on the server and it tells me something like it's open by the IIShelper. Through hours of work I narrowed to down to this stuff. Why is it keeping the file in use?</p>
  
  <pre><code>    public static void MergeFiles(string destinationFile, string[] sourceFiles)
      {
  
          int f = 0;
          // we create a reader for a certain document
          PdfReader reader = new PdfReader(sourceFiles[f]);
          // we retrieve the total number of pages
          int n = reader.NumberOfPages;
          // step 1: creation of a document-object
          Document document = new Document(reader.GetPageSizeWithRotation(1));
          // step 2: we create a writer that listens to the document
          PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
          // step 3: we open the document
          document.Open();
          PdfContentByte cb = writer.DirectContent;
          PdfImportedPage page;
          int rotation;
          if(reader.IsEncrypted() == false)
          {
              // step 4: we add content
              while (f &lt; sourceFiles.Length)
              {
                  int i = 0;
                  while (i &lt; n)
                  {
                      i++;
                      document.SetPageSize(reader.GetPageSizeWithRotation(i));
                      document.NewPage();
                      page = writer.GetImportedPage(reader, i);
                      rotation = reader.GetPageRotation(i);
                      if (rotation == 90 || rotation == 270)
                      {
                          cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                      }
                      else
                      {
                          cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                      }
                  }
                  f++;
                  if (f &lt; sourceFiles.Length)
                  {
                      reader = new PdfReader(sourceFiles[f]);
                      // we retrieve the total number of pages
                      n = reader.NumberOfPages;
                  }
  
              }
          }
          else
          {
              //is encrypted
          }
          // step 5: we close the document
          document.Close();
          reader.Close();
          reader.Dispose();
  
  
      }
  </code></pre>
  
  <p>Thanks in advance</p>