Q: Exception message: The process cannot access the file because it is being used by another process I am generating a pdf using the code below. Then it populates a gridview so that the user can click on the PDF that was just generated. I am getting an Exception message: Exception type: IOException 

The process cannot access the file '\Server\PDFs\PE10091026-Rev.pdf'
  because it is being used by another process.

If I generate another PDF then the previous one can be opened. 
Any idea what is holding the lock on it if no one has the file open? 
Dim Doc1 As New Document
Dim path As String = "\\server\PDFs\"
Dim myUniqueFileName = String.Format("{0}.pdf", Session("FileName") & "-Rev")
Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(Doc1, New FileStream(path & myUniqueFileName, FileMode.Create))

Doc1.Open()
Dim test As String
test = Session("PDF")
Dim PDFHeader As String
PDFHeader = Session("Header")
Dim imagepath As String = Server.MapPath(".") & "/images/Header.png"
Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imagepath)
image.ScalePercent(70.0F)
Dim line1 As New iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1)

Doc1.Add(image)
Doc1.Add(New Paragraph(PDFHeader))
Doc1.Add(New Chunk(line1))
Doc1.Add(New Paragraph(test))
Doc1.Close()
Doc1.Dispose()


A: You probably need to dispose the FileStream using FileStream.Dispose() or by using a Using statement. Currently the  FileStream is still opened in create mode when you try to open it the second time.
Using fs As New FileStream(Path & myUniqueFileName, FileMode.Create)

    Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(Doc1, fs)
    Doc1.Open()

    Dim test As String
    test = Session("PDF")
    Dim PDFHeader As String
    PDFHeader = Session("Header")
    Dim imagepath As String = Server.MapPath(".") & "/images/Header.png"
    Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imagepath)
    image.ScalePercent(70.0F)
    Dim line1 As New iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1)

    Doc1.Add(image)
    Doc1.Add(New Paragraph(PDFHeader))
    Doc1.Add(New Chunk(line1))
    Doc1.Add(New Paragraph(test))
    Doc1.Close()
    Doc1.Dispose()

End Using

