处理PDF时如何复制文件并释放原文件,避免多人无法同时读取?
解决PDF文件被锁定无法多用户读取的问题
问题核心在于你直接操作原PDF文件时,AddPage(page)会让新的PdfDocument持有原文档页面的底层资源引用——即便用了ReadOnly模式,原文件也会被持续锁定,直到新文档资源被完全释放。
解决思路很直接:先把原PDF复制到临时目录,操作这个临时副本,原文件就能立刻被释放,不会影响其他用户读取。
修改后的代码如下:
// 1. 复制原文件到临时目录,生成临时副本路径 string tempOriginalPath = Path.Combine(Global.GetTempFolder(), $"temp_{Path.GetFileName(drawingFileName)}"); File.Copy(drawingFileName, tempOriginalPath, overwrite: true); this.document = new PdfDocument(); // 2. 操作临时副本,而非原文件 using (PdfDocument docOri = PdfReader.Open(tempOriginalPath, 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); } } } // 3. 保存最终生成的PDF string filename = Path.GetFileName(drawingFileName); this.fileName = Path.Combine(Global.GetTempFolder(), filename); this.document.Save(this.fileName); // 4. 可选:删除临时副本,清理临时资源 File.Delete(tempOriginalPath); // 打开生成的文件 ProcessStartInfo startInfo = new ProcessStartInfo(this.fileName); Process.Start(startInfo);
关键说明:
File.Copy完成后,原文件会立刻被释放,其他用户可正常读取- 所有读取、页面复制操作都针对临时副本,彻底避免锁定原文件
- 操作完成后删除临时副本,防止临时目录堆积无用文件
内容的提问来源于stack exchange,提问作者Siegfried.V
相关产品推荐
相关产品推荐

