Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 进程无法访问文件错误-iTextSharp_C#_Asp.net_File Io_Itextsharp - Fatal编程技术网

C# 进程无法访问文件错误-iTextSharp

C# 进程无法访问文件错误-iTextSharp,c#,asp.net,file-io,itextsharp,C#,Asp.net,File Io,Itextsharp,我有下面的函数使用iTextSharp库创建PDF public static string SavePDF(int id, bool isApproved) { string path = ""; using (Document doc = new Document(PageSize.A4, 42, 53, 70, 46)) { PdfHelper page = new PdfHelper();

我有下面的函数使用iTextSharp库创建PDF

    public static string SavePDF(int id, bool isApproved)
    {
        string path = "";
        using (Document doc = new Document(PageSize.A4, 42, 53, 70, 46))
        {
            PdfHelper page = new PdfHelper();
            path = System.Web.HttpContext.Current.Server.MapPath("~/Files/File_" + id + ".pdf");

            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                using (PdfWriter pdfWriter = PdfWriter.GetInstance(doc, fs))
                {
                    pdfWriter.PageEvent = page;

                    doc.Open();
                    //code to add contents to pdf

                    doc.Close();
                    fs.Close(); 
                } 
            } fs.Dispose();
        }
        System.Threading.Thread.Sleep(1000);
        return path;
    }
在.NET应用程序中调用上述函数两次。但是,在第二次呼叫中,它给了我以下错误:

System.IO.IOException:进程无法访问文件“C:\inetpub\wwwroot\xxxxx-website\Files\file\u 1605.pdf”,因为另一个进程正在使用该文件。在System.IO.FileStream.Init(字符串路径、文件模式、文件访问权限、Int32权限、布尔用户权限、文件共享共享、Int32缓冲区大小、文件选项选项、安全属性secAttrs、字符串msgPath、布尔bFromProxy、布尔useLongPath)处的System.IO.Error.WinIOError(Int32 errorCode、字符串maybeFullPath)在System.IO.FileStream..ctor(字符串路径、文件模式、文件访问访问、文件共享、Int32 bufferSize、文件选项选项、字符串msgPath、布尔bFromProxy)在System.IO.FileStream..ctor(字符串路径、文件模式)

我对这个错误感到非常困惑,因为我已经多次修改了代码,包括使用语句以及对象的Close()和Dispose()。我甚至使用线程来等待操作首先完成,但我似乎得到了相同的错误


任何帮助都将不胜感激。

作为一项测试,您只能看到第一次调用释放文件需要多长时间?(即使用while循环并尝试/catch;不要将此代码留在那里)-或者您已经这样做了,并且它在停止应用程序之前从未被释放?我注意到一件事-为什么您要在
中使用(FileStream fs=new FileStream(path,FileMode.Create))
块调用
fs.Dispose()
?您知道
使用()
将为您调用Dispose吗?此方法是否可能同时调用两次?如果是这样,一个互斥或类似的东西可能会有所帮助。如果您在本地计算机上运行,您可以尝试运行或。我还建议使用更明确的
FileStream
声明来拒绝其他人的访问,
使用(var fs=newfilestream(path,FileMode.Create,FileAccess.Write,FileShare.None))
@ChrisHaas对该方法的第二次调用是在第一次调用大约10秒后进行的。我唯一要尝试的另一件事是使用语句交换
的顺序。您的
FileStream
应该首先出现,然后是
文档
,最后是
PdfWriter