Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# - Pdf file using by an other process eror on Bitmiracle.Docotic.Pdf

I am trying to modify the metadata of a PDF file using Bitmiracle.Docotic.Pdf. I derived the following example from BitMiracle's Github page. Metadata.pdf is an existing PDF document in my PC.

string pathToFile = "Metadata.pdf";
using (PdfDocument pdf = new PdfDocument(pathToFile))
{
    pdf.Info.Author = "Sample Browser application";
    pdf.Info.Subject = "Document metadata";
    pdf.Info.Title = "Custom title goes here";
    pdf.Info.Keywords = "pdf, Docotic.Pdf";
    
    pdf.Save(pathToFile);
}

I get the error like this:

System.IO.IOException: The process cannot access the file 'Metadata.pdf' because it is being used by another process.

How can I solve this?

like image 701
Quince Avatar asked Jan 17 '26 23:01

Quince


1 Answers

The file is locked by a PdfDocument instance. Instead, save to a temporary file or stream and copy the temporary data to the original place after disposing of PdfDocument. Sample code:

string tempFile = ...;
using (var pdf = new PdfDocument(pathToFile))
{
    ...
    pdf.Save(tempFile);
}

File.Copy(tempFile, originalFileName, true);
like image 154
Vitaliy Shibaev Avatar answered Jan 20 '26 13:01

Vitaliy Shibaev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!