c# - 无法访问该文件,因为它正被另一个进程使用

标签 c# asp.net itextsharp pdfstamper

我的网络方法在我的 %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/

相关文章:

c# - ItextSharp (Itext) - 为段落设置自定义字体

c# - 使用自动实现的属性或我们自己实现属性

c# - JSON 反序列化 : How to get values out of a JSON array of objects

c# - 如何在 C# 中找到转发器的 div 控件?

Asp.net:ScriptManager 不工作

jquery - 点击展开一个div

c# - 在 iTextSharp 中以从右到左(双向)语言反转字符串

c# - 如何取消订阅使用 lambda 表达式的事件?

asp.net - 无法将调试器从 VS 2017 连接到 ASP.NET CORE 2.2.1 应用程序的 Azure 应用程序服务

来自 base64 的 C# Asp.net RazorPdf/iTextSharp 图像