Home > Blockchain >  DeleteFile() doesn't work in Embarcadero C Builder
DeleteFile() doesn't work in Embarcadero C Builder

Time:12-20

I load several pdfs into Embarcadero C and digitally sign them with Gnostice pdfToolkit Vcl. The problem is deleting the unsigned pdf when it is already signed. This is the code:

gtPDFDocumento->LoadFromFile("no_firmado.pdf");
gtPDFDocumento->AddSignature(firma_digital.pfx);
gtPDFDocumento->SaveToFile("firmado.pdf");

//You have to reload the pdf because if it does not give an error
gtPDFDocumento->LoadFromFile("firmado.pdf");
//
if(!DeleteFile("no_firmado.pdf"){
    int e = GetLastError();
    AnsiString error = SysErrorMessage(e);
    ShowMessage(error);
    return;
}

This is the result of the error with GetLastError():

The process does not have access to the file because it is being used by another process.

I would like to know how I can unlock the unsigned pdf in order to delete it.

CodePudding user response:

You still have the no_firmado.pdf file open from the line where you load it originally.

gtPDFDocumento->LoadFromFile("no_firmado.pdf");

This is why you are getting this error.

Close the file explicitly and after that, it can be deleted.

 // Free Resources
 gtPDFDocumento->Reset();

 // Destroy PDF document object
 FreeAndNil(gtPDFDocumento);
 // After this point gtPDFDocumento can not be used unless reinitialized.

Now you can call DeleteFile(...)

CodePudding user response:

I had already tried that code and it gives the same error:

gtPDFDocument->LoadFromFile("not_signed.pdf");
gtPDFDocument->AddSignature(digital_signature.pfx);
gtPDFDocument->SaveToFile("signed.pdf");

//You have to reload the pdf because if it does not give an error
gtPDFDocument->LoadFromFile("signed.pdf");
//
// Free Resources
gtPDFDocument->Reset();
// Destroy PDF document object
FreeAndNil(gtPDFDocument);
// After this point gtPDFDocument can not be used unless reinitialized.
if(!DeleteFile("not_signed.pdf"){
inte = GetLastError();
AnsiString error = SysErrorMessage(e);
ShowMessage(error);
return;
}

Thank you!!

  • Related