2010-06-05 71 views
1

我想將.xps文檔加載到我的WPF應用程序中的DocumentViewer對象中。一切工作正常,除非我嘗試加載資源.xps文檔。我可以在使用絕對路徑時加載.xps文檔,但是當我嘗試加載資源文檔時,它會拋出「DirectoryNotFoundException」.NET WPF應用程序:加載資源.XPS文檔

下面是加載文檔的代碼示例。

 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的;組件\文檔\ MyDocument.xps’

看來,它正試圖從道路搶.XPS文件,就好像它是計算機上的實際路徑,而不是試圖從存儲的應用程序中的資源.XPS搶。

回答

1

XpsDocumentctor可以接受的文件路徑或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(); 
+0

即使做了上面列出的內容,看起來它仍然試圖讀取作爲實際路徑放入參數的任何字符串。例如,我在參數中放入了@「Docs/Mydocument.xps」,並且因爲它正在查看C:\ docs \ mydocument.xps路徑而引發錯誤。 – contactmatt 2010-06-06 03:05:21

+1

我在編輯我的帖子後,意識到'XpsDocument' ctor接受文件路徑,而不是URI。 – repka 2010-06-07 14:40:33

+0

我再次編輯它添加與包裹搗毀。醜,但它的作品。 – repka 2010-06-07 15:07:42

相關問題