Error trying to generate PDF file with the same name

Asked

Viewed 165 times

1

When trying to generate PDF files, I often come across as the error:

Mensage: The process cannot access the file’D:.... 23381708.pdf' because it is being used by Another process.

Which tells me that the file cannot 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 another one that I created just before.

To try to get around this situation, 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) return always that error.

1 answer

2


Lacked force the Dispose() at the end of the creation of the document:

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();
}
  • With the use of .Dispose(); the same happens, that is, sometimes gives the error. I will try the second suggestion

  • The second way also happens the same

  • What I am doing is creating the file and sending it by email as an attachment. You may have something to do with sending the email and getting blocked in the process?

  • No, I think it’s the FileStream anonymous that’s causing this.

  • So I have to start/create it before? Or match something before write?

  • Yeah, and do the Dispose() shortly after.

  • I’m putting the using and the Dispose() after closing the document. That’s what you mean?

  • I’d better edit the answer.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.