3

I am dealing with a SQLCE database in which one of the tables has an image type column which stores the raw binary data of an XPS document.

I am reading this data into a byte[], and then saving it to disk as follows:

File.WriteAllBytes(myPath, myByteArray);

This works. I can double-click the file at myPath and view it in Microsoft XPS Viewer. And if I rename it as a ZIP file then I can open it in WinZip.

But when I try and load the exact same file into a DocumentViewer in my WPF app as follows:

var xpsDocument = new XpsDocument(myPath, FileAccess.Read);
var sequence = xpsDocument.GetFixedDocumentSequence();
// ...

It fails on the first line with the following exception:

File contains corrupted data.

A System.IO.FileFormatException occurred
   at MS.Internal.IO.Zip.ZipIOEndOfCentralDirectoryBlock.FindPosition(Stream archiveStream)
   at MS.Internal.IO.Zip.ZipIOEndOfCentralDirectoryBlock.SeekableLoad(ZipIOBlockManager blockManager)
   at MS.Internal.IO.Zip.ZipArchive..ctor(Stream archiveStream, FileMode mode, FileAccess access, Boolean streaming, Boolean ownStream)
   at MS.Internal.IO.Zip.ZipArchive.OpenOnFile(String path, FileMode mode, FileAccess access, FileShare share, Boolean streaming)
   at System.IO.Packaging.ZipPackage..ctor(String path, FileMode mode, FileAccess access, FileShare share, Boolean streaming)
   at System.IO.Packaging.Package.Open(String path, FileMode packageMode, FileAccess packageAccess, FileShare packageShare, Boolean streaming)
   at System.Windows.Xps.Packaging.XpsManager..ctor(String path, FileAccess packageAccess, CompressionOption compressionOption)
   at System.Windows.Xps.Packaging.XpsDocument..ctor(String path, FileAccess packageAccess, CompressionOption compressionOption)

I don't understand why the file will open in Microsoft XPS Viewer / WinZip (suggesting it is not, in fact, corrupted), but not through my code.

And frustratingly, it's not consistent. For some of the values in the database it works, for others it doesn't. (Although it is consistent which values will fail and which won't).

Has anybody come across this issue before, or know of a reason/fix?

Ross
  • 4,460
  • 2
  • 32
  • 59

1 Answers1

0

You probably need to read the bytes as a stream and use xps packaging. This solution worked for me:

var webClient = new System.Net.WebClient();
var data = webClient.DownloadData(myPath);
var package = System.IO.Packaging.Package.Open(new System.IO.MemoryStream(data));
var xpsDocument = new System.Windows.Xps.Packaging.XpsDocument(package,
                                                          System.IO.Packaging.CompressionOption.SuperFast,
                                                          myPath);
var sequence = xpsDocument.GetFixedDocumentSequence();
Alex
  • 616
  • 9
  • 12