在我的WPF应用程序中,我通过构建其XAML标记作为字符串来创建
我需要在文档中包含一个图像,因此为了实现这一点,我创建并保存图像作为临时文件在临时目录中,并在我的
但问题是,我的应用程序保留了对该图像的文件锁定,直到应用程序退出。
我正在清理所有资源。我的生成的XPS文件上没有文件锁定-只有图像文件。如果我注释掉创建XPS文件的代码部分,那么图像文件就不会被锁定。
我的代码(我正在使用.NET 4 CP):
FlowDocument
,然后使用XamlReader.Parse
将字符串转换为FlowDocument
对象,然后将其保存到XPS文档文件。它运行良好。我需要在文档中包含一个图像,因此为了实现这一点,我创建并保存图像作为临时文件在临时目录中,并在我的
FlowDocument
的XAML中引用它的绝对路径。这也可以正常工作-在XPS文档创建过程中,图像实际上被嵌入到XPS文档中,这很好。但问题是,我的应用程序保留了对该图像的文件锁定,直到应用程序退出。
我正在清理所有资源。我的生成的XPS文件上没有文件锁定-只有图像文件。如果我注释掉创建XPS文件的代码部分,那么图像文件就不会被锁定。
我的代码(我正在使用.NET 4 CP):
var xamlBuilder = new StringBuilder();
// many lines of code like this
xamlBuilder.Append(...);
// create and save image file
// THE IMAGE AT THE PATH imageFilePath IS GETTING LOCKED
// AFTER CREATING THE XPS FILE
var fileName = string.Concat(Guid.NewGuid().ToString(), ".png");
var imageFilePath = string.Format("{0}{1}", Path.GetTempPath(), fileName);
using (var stream = new FileStream(imageFilePath, FileMode.Create)) {
var encoder = new PngBitmapEncoder();
using (var ms = new MemoryStream(myBinaryImageData)) {
encoder.Frames.Add(BitmapFrame.Create(ms));
encoder.Save(stream);
}
stream.Close();
}
// add the image to the document by absolute path
xamlBuilder.AppendFormat("<Paragraph><Image Source=\"{0}\" ...", imageFilePath);
// more lines like this
xamlBuilder.Append(...);
// create a FlowDocument from the built string
var document = (FlowDocument) XamlReader.Parse(xamlBuilder.ToString());
// set document settings
document.PageWidth = ...;
...
// save to XPS file
// THE XPS FILE IS NOT LOCKED. IF I LEAVE OUT THIS CODE
// AND DO NOT CREATE THE XPS FILE, THEN THE IMAGE IS NOT LOCKED AT ALL
using (var xpsDocument = new XpsDocument(filePath, FileAccess.ReadWrite)) {
var documentWriter = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
documentWriter.Write(((IDocumentPaginatorSource) document).DocumentPaginator);
xpsDocument.Close();
}
(实际上,它是在临时目录中动态生成的图像这一事实并不重要 - 如果我硬编码任何计算机上的图像文件路径,它都会被锁定。)
人们可能会认为 XPS 创建代码中存在导致文件锁定的 bug。
还有其他什么我可以尝试吗?或者有没有办法通过代码来解除文件锁定?