3

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?

Quince
  • 144
  • 11

2 Answers2

2

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);
Vitaliy Shibaev
  • 1,420
  • 10
  • 24
1

It looks like another process is using the file and it's "locked". While multiple processes can access the file in read-only mode, only one can access it in read-write mode (this locks the file).

First step would be figuring out which processes are using that file. It might be opened Acrobat Reader in background or even by Explorer.

Useful tool which I use is from Microsoft that checks and can release files is called File Locksmith in their PowerToys utilities. With it you can check if file is opened by any other process than your code and terminate that process, to release the file.

https://learn.microsoft.com/en-us/windows/powertoys/file-locksmith

You can get PowerToys here: https://learn.microsoft.com/en-us/windows/powertoys/

If the only process using the file is your code it means that there is something wrong in the code, but since you said that you copied from the example on the documentation page, it's unlikely that this is the case.

Martin Ferenec
  • 57
  • 1
  • 1
  • 9