承认我是C#和Asp.net的新手。
My Web App在文件夹中创建pdf(iTextSharp)文件,并将结果发布到另一个网页中。 当任何人返回页面并重新创建一个同名的新pdf(已修改)时,您会收到以下错误:
该进程无法访问该文件 'C:\ inetpub \ wwwroot \ RAPC \ PDF \ 10-2012_file1.pdf'因为它正在 被另一个过程使用。
描述:执行期间发生未处理的异常 当前的网络请求。请查看堆栈跟踪了解更多信息 有关错误的信息以及它在代码中的起源。
异常详细信息:System.IO.IOException:进程无法访问文件'C:\ inetpub \ wwwroot \ RAPC \ PDF \ 10-2012_file1.pdf',因为它正由另一个人使用过程
来源错误: 第132行:
FileStream stream = new FileStream(path + "/" + subdata + "_" + CodCli + "_" + DrR1_2 + "_" + G_S_2 + "_" + Data_2 + ".pdf", FileMode.Create);*
我的代码:
// Filestream and PDF create
FileStream stream = new FileStream(path + "/" + subdata + "_" + CodCli + "_" + DrR1_2 + "_" + G_S_2 + "_" + Data_2 + ".pdf", FileMode.Create);
PdfWriter.GetInstance(doc, stream);
doc.Open();
// Table
PdfPTable tableX = new PdfPTable(2);
PdfPCell cell = new PdfPCell();
tableX.WidthPercentage = 100;
tableX.DefaultCell.Border = 0;
cell.AddElement(image);
cell.PaddingLeft = 30f;
cell.Border = 0;
tableX.AddCell(cell);
...
doc.Close();
stream.Close();
屏幕截图:https://docs.google.com/open?id=0ByUzt8ssZaf7Z2YtVXlnRmo3SGM
似乎PDF已被w3p IIS Worker Process锁定。几分钟后,文件恢复正常状态。
我希望pdf文件立即解锁,以便用户可以修改和重新保存PDF。
谢谢
答案 0 :(得分:0)
正如Ian Kemp所说in the comments,将FileStream
对象包装在using
块中是个好主意。像这样:
using (FileStream stream = new FileStream(path + "/" + subdata + "_" + CodCli + "_" + DrR1_2 + "_" + G_S_2 + "_" + Data_2 + ".pdf", FileMode.Create))
{
// ...the rest of your code
}
这将确保您的对象得到妥善处理,希望每次都释放资源,这样可以防止错误发生。