C# 在Mogradoc WPF中使用section.AddImage()后,释放对图像文件的锁定
我有以下代码来生成报告PDF,上载它,然后删除生成中使用的临时图像:C# 在Mogradoc WPF中使用section.AddImage()后,释放对图像文件的锁定,c#,wpf,asp.net-mvc-4,pdfsharp,migradoc,C#,Wpf,Asp.net Mvc 4,Pdfsharp,Migradoc,我有以下代码来生成报告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 cons
// 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.
我已经对代码进行了调试,以确保在调用pdfrender.RenderDocument()之前可以访问该文件,如代码注释中所述
PdfDocumentRenderer类没有close或dispose方法,并且它没有实现IDisposable,因此我不能使用using块
如何释放文件上的锁?尝试使用“PDFsharp MigraDoc GDI”包而不是“PDFsharp MigraDoc WPF”包
顺便说一句:如果你想在“黑匣子”中进行更改,可以下载完整的源代码。我修复了修改PdfSharp.Drawing\XImage.cs的“位图图像锁定文件”错误,如下所示: 替换第114行:
this.wpfImage = new BitmapImage(new Uri(path)); // AGHACK
与
这对我有用。你试过先用谷歌搜索吗
BitmapCacheOption.OnLoad
据称是一种解决方案(仅供参考:我不知道什么是Migradoc)。我已经在谷歌上彻底搜索过了,是的。MigraDoc是一个库(我相信)与PDFSharp一起生成PDF。我使用nuget包管理器获得了它,因此我认为我无法深入源代码来更改任何构造函数。对位图缓存的更改没有帮助,因为我无法控制位图,AddImage()函数只接受图像的路径,因此该函数中发生的事情目前对我来说是一个黑匣子。我无法使用GDI包,因为我的应用程序正在Azure云上运行,我遇到以下错误:“内部错误。无法检索字体数据。“。看来我唯一的解决方案可能是对源代码进行自己的更改?如果这是一个简单的更改,为什么GDI版本中没有修复它?@Starky:这不是GDI构建的问题,而是WPF的问题。我们还没有在Nuget上发布WPF构建,但我们目前计划在今年晚些时候在那里发布它——修复程序也将包括在内。要快速修复,请自己进行更改。
BitmapImage imgTemp = new BitmapImage();
imgTemp.BeginInit();
imgTemp.CacheOption = BitmapCacheOption.OnLoad;
imgTemp.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
imgTemp.UriSource = new Uri(path);
imgTemp.EndInit();
this.wpfImage = imgTemp;