我有以下代码用于生成报告PDF、上传并删除生成中使用的临时图像:
当我尝试删除图像目录时,会引发以下异常:
// Generate document and then add a section with an image
var document = new Document {Info = {Title = "Results"}};
var section = document.AddSection();
var logo = section.AddImage(logoPath);
// Render the PDF
const PdfFontEmbedding embedding = PdfFontEmbedding.Always;
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(unicode, embedding);
pdfRenderer.Document = document;
pdfRenderer.RenderDocument(); // This is the line which locks the files
// Save the PDF to a memory stream and upload it to azure blob storage
var reportPath = "";
using (var stream = new MemoryStream())
{
pdfRenderer.Save(stream, false);
reportPath = UploadBlob("reports", "Report.pdf", stream);
}
// Delete the local copy of the logo - this is where the exception occurs
Directory.Delete(Directory.GetParent(logoPath).ToString(), true);
当我尝试删除图像目录时,会引发以下异常:
An exception of type 'System.IO.IOException' occurred in mscorlib.dll but was not handled in user code
Additional information: The process cannot access the file 'Capture.PNG' because it is being used by another process.
在调用pdfRenderer.RenderDocument()之前,我已经通过代码进行了调试,以确保文件是可访问的,正如代码注释中所述。
PdfDocumentRenderer类没有close或dispose方法,也没有实现IDisposable接口,因此我无法使用using块。
我该如何释放文件上的锁定?
BitmapCacheOption.OnLoad
可能是一个解决方案(顺便说一下:我不知道什么是 Migradoc)。 - Sinatr