Dot-Net

WPF DocumentViewer 不發布 XPS 文件

  • September 7, 2016

我正在開發一個打開並顯示 XPS 文件的 WPF 應用程序。當應用程序關閉時,規範是應用程序應刪除打開的 XPS 文件以進行清理。但是,當打開某個 XPS 文件時,應用程序會在嘗試刪除該文件時拋出該文件仍在使用中的異常。這有點奇怪,因為它僅在打開特定的 XPS 文件時發生,並且僅在您超出第一頁時才會發生。

我使用的一些程式碼如下所示:

打開 XPS 文件:

DocumentViewer m_documentViewer = new DocumentViewer();
XpsDocument m_xpsDocument = new XpsDocument(xpsfilename, fileaccess);
m_documentViewer.Document = m_xpsDocument.GetFixedDocumentSequence();
m_xpsDocument.Close();

導航 XPS 文件:

m_documentViewer.FirstPage();
m_documentViewer.LastPage();
m_documentViewer.PreviousPage();
m_documentViewer.NextPage();

關閉 DocumentViewer 對象並刪除文件:

m_documentViewer.Document = null;
m_documentViewer = null;
File.Delete(xpsfilename);

這一切都非常基本,並且可以與我們測試的其他文件一起使用。但是對於特定的 XPS 文件,會彈出一個異常,指出要刪除的文件仍在使用中。

我的程式碼有什麼問題或遺漏嗎?

謝謝!

使 xpsDocument 成為成員,然後不要在其上呼叫 close() :)

您需要關閉打開分配給查看器的 XpsDocument 的 System.IO.Packaging.Package。此外,如果您希望能夠在同一個應用程序會話中再次打開同一個文件,則必須從 PackageStore 中刪除該包。

嘗試

var myXpsFile = @"c:\path\to\My XPS File.xps";
var myXpsDocument = new XpsDocument(myXpsFile);
MyDocumentViewer.Document = myXpsDocument;

//open MyDocumentViwer's Window and then close it
//NOTE: at this point your DocumentViewer still has a lock on your XPS file
//even if you Close() it
//but we need to do something else instead

//Get the Uri from which the system opened the XpsPackage and so your XpsDocument
var myXpsUri = myXpsDocument.Uri; //should point to the same file as myXpsFile

//Get the XpsPackage itself
var theXpsPackage = System.IO.Packaging.PackageStore.GetPackage(myXpsUri);

//THIS IS THE KEY!!!! close it and make it let go of it's file locks
theXpsPackage.Close();

File.Delete(myXpsFile); //this should work now

//if you don't remove the package from the PackageStore, you won't be able to
//re-open the same file again later (due to System.IO.Packaging's Package store/caching
//rather than because of any file locks)
System.IO.Packaging.PackageStore.RemovePackage(myXpsUri);

是的,我知道您可能沒有打開帶有包的 XpsDocument,甚至可能不知道它是什麼——或關心它——但是 .NET 在幕後為您“完成”了它並且忘記了自己進行清理。

引用自:https://stackoverflow.com/questions/283027