我的网络方法在我的 %temp% 文件夹中创建了一个 pdf 文件,并且可以正常工作。然后我想使用下面的代码向该文件添加一些自定义字段(元)。
类 PdfStamper
生成一个 IOException
,无论我使用它的 .Close()
方法还是 using
block 刚刚结束。仍然持有文件句柄的进程是 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<string, string> 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();
处抛出异常,更准确地说:
The process cannot access the file 'C:\Users[my username]\AppData\Local\Temp\53b96eaf-74a6-49d7-a715-6c2e866a63c3.pdf' because it is being used by another process.
要么是我忽略了一些明显的东西,要么是我尚未意识到的 PdfStamper
类存在问题。使用的itextsharp版本是5.3.3.0和5.4.0.0,问题是一样的。
如有任何见解,我们将不胜感激。
编辑:我目前正在“编码解决”这个问题,但我还没有找到任何解决方案。
最佳答案
您的问题是您在写入文件的同时也在读取文件。与将所有数据“加载”到内存中的某些文件类型(JPG、PNG 等)不同,iTextSharp 将数据作为流读取。您需要使用两个文件并在最后交换它们,或者您可以通过将 PdfReader
绑定(bind)到文件的字节数组来强制 iTextSharp“加载”第一个文件。
PdfReader reader = new PdfReader(System.IO.File.ReadAllBytes(filePath));
关于c# - 无法访问该文件,因为它正被另一个进程使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15617883/