Search code examples
c#pdfsharp

Copy a PDF avoids reading from several users


I made a small function, that reads a PDF, adds some table on original PDF, then saves as a new file. The problem is when I use it, it seems to block the original file, and several users cannot read it at the same time.

this.document = new PdfDocument();
using (PdfDocument docOri = PdfReader.Open(drawingFileName, PdfDocumentOpenMode.ReadOnly))
{
    foreach (PdfPage page in docOri.Pages)
    {
        this.currentPage = this.document.AddPage(page);
        this.graphics = XGraphics.FromPdfPage(this.currentPage);
        if (configVentilation.IsActivated)
        {
            displayVentilationTable(listDetails, configVentilation);
        }
    }
}
string filename = System.IO.Path.GetFileName(drawingFileName);
this.fileName = Global.GetTempFolder() + filename;
this.document.Save(this.fileName);
ProcessStartInfo startInfo = new ProcessStartInfo(this.fileName);
Process.Start(startInfo);

It seems by using this.document.AddPage(page), original document gets used, and then other users cannot open it anymore. How can I make a copy, and "free" original file?


Solution

  • The file system doesn't always lift locks immediately as soon as the handle is freed. That's quite annoying but well known.

    If you need to ensure the original is still readable while you are working on its data and you intend to save the changes to a different file anyway, the easiest (imho) way to go about it is:

    1. Create a copy of the original.
    2. Open and work on the copy.
    3. Save changes back to said copy.

    If something is observing the folder for new entries, you may want to copy to a "work-in-progress" folder and move the file back when you are done.