使用Bitmiracle.Docotic.Pdf修改PDF元数据遇文件占用错误如何解决
解决Bitmiracle.Docotic.Pdf修改PDF元数据时的文件占用问题
你遇到的错误是因为PdfDocument打开原文件后会保持文件锁定,此时直接调用Save(pathToFile)尝试覆盖原文件就会触发IO异常。以下是几种可行的解决方法:
方法1:从内存流加载文件,避免锁定原文件
先把原文件读取到内存流中,再用内存流实例化PdfDocument,这样原文件不会被锁定,后续可以直接覆盖保存:
string pathToFile = "Metadata.pdf"; byte[] fileBytes = File.ReadAllBytes(pathToFile); using (MemoryStream ms = new MemoryStream(fileBytes)) using (PdfDocument pdf = new PdfDocument(ms)) { 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); }
方法2:关闭所有占用目标文件的进程
检查是否有其他程序(比如PDF阅读器、文件编辑器、其他后台进程)正在打开Metadata.pdf,关闭这些程序后再运行代码即可。
方法3:先保存到临时文件,再替换原文件(更安全)
如果担心直接覆盖原文件可能出现异常导致文件损坏,可以先保存到临时文件,确认保存成功后再替换原文件:
string pathToFile = "Metadata.pdf"; string tempPath = Path.GetTempFileName() + ".pdf"; try { 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(tempPath); } // 替换原文件,同时保留原文件的备份(可选) File.Replace(tempPath, pathToFile, pathToFile + ".bak"); } finally { // 清理临时文件 if (File.Exists(tempPath)) File.Delete(tempPath); }
内容的提问来源于stack exchange,提问作者Quince
相关产品推荐
相关产品推荐

