Error trying to generate PDF file with the same name

2

When trying to generate PDF files, many times I come across the error:

  

Message: The process can not access the file 'D: .... \ 23381708.pdf' because it is being used by another process.

That tells me that the file can not be created because it is already being used by another process.

This problem occurs when I am trying to generate a document with the same name as the one I have created before.

To try to work around this, I'm trying:

//Definir tipo de documento
Document doc1 = new Document();
doc1.SetPageSize(iTextSharp.text.PageSize.A4);
doc1.SetMargins(0f, 0f, 0f, 0f);
doc1.NewPage();

var ficheiroAbs = Path.Combine((pastasLer.FirstOrDefault().PastaDestGARTratada + "/2Via"), nomeDoc);
//abrir documento para escrever
PdfWriter writer = PdfWriter.GetInstance(doc1, new FileStream(ficheiroAbs, FileMode.Create));//Erro ocorre nesta linha
doc1.Open();

//código criar documento

doc1.Close();
doc1 = new Document();

However, sometimes (not always) I always return that error.

    
asked by anonymous 02.12.2014 / 12:39

1 answer

2

Failed to force Dispose() at the end of document creation:

PdfWriter writer = PdfWriter.GetInstance(doc1, new FileStream(ficheiroAbs, FileMode.Create));//Erro ocorre nesta linha
doc1.Open();

//código criar documento

doc1.Close();
doc1.Dispose();
doc1 = new Document();

Or in a more performative way:

//Definir tipo de documento
using (Document doc1 = new Document()) 
{
    doc1.SetPageSize(iTextSharp.text.PageSize.A4);
    doc1.SetMargins(0f, 0f, 0f, 0f);
    doc1.NewPage();

    var ficheiroAbs = Path.Combine((pastasLer.FirstOrDefault().PastaDestGARTratada + "/2Via"), nomeDoc);
    //abrir documento para escrever
    using (var fileStream = new FileStream(ficheiroAbs, FileMode.Create)) {
        var writer = PdfWriter.GetInstance(doc1, fileStream);
        doc1.Open();

        //código criar documento
    }

    doc1.Close();
}
    
02.12.2014 / 18:33