无法访问该文件,因为它正由另一个进程使用

我的web方法在我的%temp%文件夹中创建一个pdf文件,该文件有效。 然后我想使用下面的代码向该文件添加一些自定义字段(meta)。

PdfStamper类生成一个IOException ,无论我使用它的.Close()方法还是using块结束。 仍然保留文件句柄的过程是webdev Web服务器本身(我在VS2010 SP1中进行调试)。

 private string AddCustomMetaData(string guid, int companyID, string filePath) { try { PdfReader reader = new PdfReader(filePath); using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { PdfStamper st = new PdfStamper(reader, fs); Dictionary info = reader.Info; info.Add("Guid", guid); info.Add("CompanyID", companyID.ToString()); st.MoreInfo = info; st.Close(); } reader.Close(); return guid; } catch (Exception e) { return e.Message; } } 

无论我尝试什么,它都会在st.Close();抛出exceptionst.Close(); ,更确切地说:

该进程无法访问文件’C:\ Users [我的用户名] \ AppData \ Local \ Temp \ 53b96eaf-74a6-49d7-a715-6c2e866a63c3.pdf’,因为它正由另一个进程使用。

要么我忽视了一些明显的东西,要么PdfStamper类的问题我还没有意识到。 使用的itextsharp的版本是5.3.3.0和5.4.0.0,问题是相同的。

任何见解将不胜感激。

编辑:我目前正在“编码”这个问题,但我还没有找到任何解决方案。

你的问题是,当你正在阅读文件时,你正在写一个文件。 与将所有数据“加载”到内存中的某些文件类型(JPG,PNG等)不同,iTextSharp将数据作为流读取。 您需要使用两个文件并在最后交换它们,或者您可以通过将PdfReader绑定到文件的字节数组来强制iTextSharp“加载”第一个文件。

 PdfReader reader = new PdfReader(System.IO.File.ReadAllBytes(filePath)); 

我建议您在打开文件时使用FileShare enumerator ,因此请尝试打开None sharing文件

  File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None); 

第一次保存文件时,请尝试.Dispose()PDF阅读器(或用于创建它的任何内容)

如果您认为它对您可行,请尝试此解决方案 – 一旦webmethod在Temp文件夹中创建文件,您需要复制文件并将其粘贴到具有不同名称的其他位置或相同位置,并将新复制的文件路径传递给PDF阅读器。