views:

189

answers:

1

I'm trying to load a .xps document into a DocumentViewer object in my WPF application. Everything works fine, except when I try loading a resourced .xps document. I am able to load the .xps document fine when using an absolute path, but when I try loading a resourced document it throws a "DirectoryNotFoundException"

Here's an example of my code that loads the document.

     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();
        }

When the DirectoryNotFoundException is thrown, it says "Could not find a part of the path : 'C:\MyProject;component\Docs\MyDocument.xps'

It appears that it is trying to grab the .xps document from that path, as if it were an actual path on the computer, and not trying to grab from the .xps that is stored as a resource within the application.

+1  A: 

XpsDocument ctor accepts either a file path or a Package instance. Here's how you can open a Package to use the latter approach:

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();
repka
Even after doing what you listed above, it appears that it is still trying to read whatever string I put into the parameter as an actual path. For example, I put in the @"Docs/Mydocument.xps" in the parameter and it threw an error because it was looking at the C:\docs\mydocument.xps path.
contactmatt
I edited my post, after realizing that `XpsDocument` ctor accepts file path, not URI.
repka
I edited it again adding mangling with packages. Ugly, but it works.
repka
You were a great help. Thank you!
contactmatt