After showing an XPS file in the WPF DocumentViewer, and closing the DocumentViewer instance, the XPS file is locked and I cannot delete it. I need to release the lock on the XPS file so I can delete it, write another one with the same name, and optionally display that new XPS file in a new DocumentViewer instance. I need to do this in the same app instance - without having to close the app (this is a Print Preview scenario).
In other words, how would I get the following code to run without throwing an exception at the "File.Delete(tempXpsFile);" statement?
var tempXpsFile = @"c:\path\to\Temporary.xps";
var previewWindow = new Window();
var docViewer = new DocumentViewer();
previewWindow.Content = docViewer;
GenerateXpsFile(tempXpsFile);
var xpsDocument = new XpsDocument(tempXpsFile);
previewWindow.ShowDialog();
File.Delete(tempXpsFile); //this will throw an exception due to a file lock on tempXpsFile
GenerateXpsFile(tempXpsFile); //assume this generates a different file
//otherwise the scenario doesn't make sense as we could just skip the above delete
//and this statement and re-use the same file
previewWindow = new Window();
docViewer = new DocumentViewer();
previewWindow.Content = docViewer;
previewWindow.ShowDialog();
Closing the app does release the file lock, as mentioned in WPF DocumentViewer doesn't release the XPS file, but that is not an option in this scenario.