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?
7
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:
- Create a copy of the original.
- Open and work on the copy.
- 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.
3
You can read the PDF file from a stream and you can open the stream with the sharing and locking settings you need. And you can close the stream immediately after reading the PDF.
Maybe use code like this:
var bytes = File.ReadAllBytes(filename);
Stream stream = new MemoryStream(bytes);
This will still lead to problems if other users open the file with read/write access or without allowing shared read access.
3