Search code examples
wpfexceptionxpssavefiledialog

WPF: XPSPackagingException


whats wrong with my code. when it tries to overwrite an existing .xps file, error pops.

enter image description here

Here's my code

                string filename = dlg.FileName;

                XpsDocument xpsDoc = new XpsDocument(filename, FileAccess.ReadWrite);
                XpsDocumentWriter xpsWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc);
                FlowDocument flow = (((((chatHistoryPage.LayoutRoot as Grid).Children[7] as ContentControl).Content) as FlowDocumentPageViewer).Document as FlowDocument);

                xpsWriter.Write((flow as IDocumentPaginatorSource).DocumentPaginator);
                xpsDoc.Close();

Thank you


Solution

  • The line XpsDocument xpsDoc = new XpsDocument(filename, FileAccess.ReadWrite); isn't opening a new, empty XPS document, it's opening the existing one on disk. As the exception mentions, this document already contains a root FixedDocumentSequence. In order to completely overwrite an XPS document, you need to delete the existing XPS file before you attempt to save a new one in its place.

    Your best bet is probably to call Package.Open with a FileMode of OpenOrCreate | Truncate, and then feed that package into the call to the XpsDocument constructor.