c# - new XpsDocument(string, FileAccess) 失败并显示 "File contains corrupted data",即使文件未损坏

标签 c# wpf corruption xps xpsdocument

我正在处理一个 SQLCE 数据库,其中一个表有一个 image 类型的列,它存储 XPS 文档的原始二进制数据。

我正在将此数据读入 byte[],然后按如下方式将其保存到磁盘:

File.WriteAllBytes(myPath, myByteArray);

这行得通。我可以双击位于 myPath 的文件并在 Microsoft XPS Viewer 中查看它。如果我将它重命名为 ZIP 文件,那么我可以在 WinZip 中打开它。

但是当我尝试将完全相同的文件加载到我的 WPF 应用程序中的 DocumentViewer 时,如下所示:

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

第一行失败,异常如下:

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)

我不明白为什么文件会在 Microsoft XPS Viewer/WinZip 中打开(暗示它实际上没有损坏),但不能通过我的代码打开。

令人沮丧的是,它并不一致。对于数据库中的某些值,它有效,而对于其他值则无效。 (尽管哪些值会失败,哪些不会失败是一致的)。

有没有人以前遇到过这个问题,或者知道原因/修复方法?

最佳答案

您可能需要将字节作为流读取并使用 xps 打包。这个解决方案对我有用:

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();

关于c# - new XpsDocument(string, FileAccess) 失败并显示 "File contains corrupted data",即使文件未损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20093396/

相关文章:

c# - 如何在桌面 C#/WPF 应用程序中同时支持本地 SQL Server CE 和远程 SQL Server?

c - C 程序读取文件并转换其字符会产生双重释放或损坏错误

mysql myisam datetime 5.6.10 到 5.5.10 表损坏

c#检查网络上登录的用户

c# - 如何在 System.Byte 上使用 MiscUtil.Operator?

c# - 不继承共享属性

WPF BitmapImage内存问题

wpf - 多台显示器上的错误坐标

c# - MVVM/NHibernate - 如何进行动态模型验证?

正常重启后 MySQL 损坏