.NET WPF应用程序:加载资源.XPS文档

时间:2010-06-05 17:17:08

标签: .net wpf xpsdocument documentviewer

我正在尝试将.xps文档加载到WPF应用程序中的DocumentViewer对象中。一切正常,除非我尝试加载资源.xps文档。我可以在使用绝对路径时加载.xps文档,但是当我尝试加载资源文档时,它会抛出“DirectoryNotFoundException”

以下是我加载文档的代码示例。

     using System.Windows.Xps.Packaging;

      private void Window_Loaded(object sender, RoutedEventArgs e)
        {
//Absolute Path works (below)
            //var xpsDocument = new XpsDocument(@"C:\Users\..\Visual Studio 2008\Projects\MyProject\MyProject\Docs\MyDocument.xps", FileAccess.Read); 
//Resource Path doesn't work (below)
var xpsDocument = new XpsDocument(@"\MyProject;component/Docs/Mydocument.xps", FileAccess.Read);
            DocumentViewer.Document = xpsDocument.GetFixedDocumentSequence();
        }

当抛出DirectoryNotFoundException时,它会显示“找不到路径的一部分:'C:\ MyProject; component \ Docs \ MyDocument.xps'

它似乎正在尝试从该路径中获取.xps文档,就好像它是计算机上的实际路径,而不是试图从作为应用程序中的资源存储的.xps中获取。 / p>

1 个答案:

答案 0 :(得分:1)

XpsDocument ctor接受文件路径或Package实例。以下是打开包使用后一种方法的方法:

var uri = new Uri("pack://application:,,,/Docs/Mydocument.xps");
var stream = Application.GetResourceStream(uri).Stream;
Package package = Package.Open(stream);
PackageStore.AddPackage(uri, package);
var xpsDoc = new XpsDocument(package, CompressionOption.Maximum, uri.AbsoluteUri);
var fixedDocumentSequence = xpsDoc.GetFixedDocumentSequence();
_vw.Document = fixedDocumentSequence; // displaying document in viewer
xpsDoc.Close();