【问题标题】:Creating XPS in WPF - used image files are being locked until my app quits在 WPF 中创建 XPS - 使用的图像文件被锁定,直到我的应用退出
【发布时间】:2025-11-30 20:05:01
【问题描述】:

在我的 WPF 应用程序中,我通过将其 XAML 标记构建为字符串来创建 FlowDocument,然后使用 XamlReader.Parse 将字符串转换为 FlowDocument 对象,然后将其保存到 XPS 文档文件中.它有效。

我需要在我的文档中包含一个图像,因此为了实现这一点,我在 temp 目录中创建并保存图像作为临时文件,然后在我的 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();
}

(实际上,它是 temp 目录中动态生成的图像这一事实无关紧要 - 如果我在机器上的任何图像文件的路径中硬编码,则会出现此问题 - 它会被锁定。)

有人会认为 XPS 创建代码中存在导致文件锁定的错误。

还有什么我可以尝试的吗?或者通过代码解除文件锁的方法?

【问题讨论】:

  • 我曾经遇到过同样的问题。我以某种方式解决了它。让我看看我是否能找到我在某个地方问过的问题(如果我什至在这里问过的话)。我认为这与使用Freeze() 方法冻结图像有关。
  • 在 FlowDocument 标记中,我尝试添加 po:Freeze="True" 属性(在根标记中使用 xmlns:po 声明) - 不幸的是没有工作。
  • 您是否尝试过这样声明图像:
  • 谢谢西蒙。不幸的是,“无”不适用于 CacheOption。但它引导我进行搜索,在其中找到了这个页面:devnewsgroups.net/group/microsoft.public.dotnet.framework/…,其中用户使用“OnLoad”CacheOption 来防止文件锁定。所以我这样做了,它有效!太棒了。
  • 顺便说一句,输入一个答案,我会奖励赏金,如果没有你的意见,我不会想出来的。

标签: wpf flowdocument xps file-locking


【解决方案1】:

您可以像这样更改您的 xaml:

<Image>
    <Image.Source>
        <BitmapImage CacheOption="None" UriSource="your path" />
    </Image.Source>
</Image>

能够使用CacheOption 参数,以指定Xaml Builder 应如何加载图像文件,因为默认值似乎对其保持锁定(似乎等待GC 完成其工作)。

这是关于 SO 的一些相关问题:How do you make sure WPF releases large BitmapSource from Memory?

【讨论】: