因为它正在被其他进程无法访问该文件 [英] Cannot access the file because it is being used by another process

查看:250
本文介绍了因为它正在被其他进程无法访问该文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Web方法在我的%TEMP%文件夹中创建一个PDF文件,并​​且工作。然后我想用下面的code以添加一些自定义字段(元)到该文件。

My web method creates a pdf file in my %temp% folder and that works. I then want to add some custom fields (meta) to that file using the code below.

PdfStamper 生成一个 IOException异常,我是否使用它的 .Close() 方法或使用块中的刚刚结束。即仍持有到文件句柄的过程是Webdev的Web服务器本身(我调试在VS2010 SP1)。

The class PdfStamper generates an IOException, whether I use its .Close() method or the using block just ends. The process that is still holding on to the file handle is the webdev web server itself (I'm debugging in 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()抛出异常; ,更precise:

该进程无法访问该文件'C:\\用户[我
  名] \\ AppData \\本地的\\ Temp \\ 53b96eaf-74a6-49d7-a715-6c2e866a63c3.pdf
  因为它被另一个过程

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,这个问题是一样的。

Either I'm overlooking something obvious or there's a problem with the PdfStamper class I'm as of yet unaware of. Versions of itextsharp used are 5.3.3.0 and 5.4.0.0, the issue is the same.

任何有识之士将大大AP preciated。

Any insight would be greatly appreciated.

编辑:我目前的编码围绕问题,但我还没有找到任何解决办法

I'm currently "coding around" the issue, but I haven't found any solution.

推荐答案

你的问题是,你正在写一个文件,而你也从中读取。不像某些文件类型(JPG,PNG等)的加载所有的数据到内存中的,iTextSharp的读取数据流。你要么需要使用两个文件,​​并在年底交换它们,或者您也可以通过绑定你的 PdfReader 该文件的字节数组强制iTextSharp的装入的第一个文件。

You're problem is that you are writing to a file while you are also reading from it. Unlike some file types (JPG, PNG, etc) that "load" all of the data into memory, iTextSharp reads the data as a stream. You either need to use two files and swap them at the end or you can force iTextSharp to "load" the first file by binding your PdfReader to a byte array of the file.

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

这篇关于因为它正在被其他进程无法访问该文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆