C# 新XpsDocument(字符串、文件访问)失败,返回“0”;文件包含损坏的数据";,即使文件没有损坏

C# 新XpsDocument(字符串、文件访问)失败,返回“0”;文件包含损坏的数据";,即使文件没有损坏,c#,wpf,corruption,xps,xpsdocument,C#,Wpf,Corruption,Xps,Xpsdocument,我正在处理一个SQLCE数据库,其中一个表有一个imagetype列,该列存储XPS文档的原始二进制数据 我正在将此数据读入一个字节[],然后将其保存到磁盘,如下所示: File.WriteAllBytes(myPath, myByteArray); var xpsDocument = new XpsDocument(myPath, FileAccess.Read); var sequence = xpsDocument.GetFixedDocumentSequence(); // ...

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

我正在将此数据读入一个
字节[]
,然后将其保存到磁盘,如下所示:

File.WriteAllBytes(myPath, myByteArray);
var xpsDocument = new XpsDocument(myPath, FileAccess.Read);
var sequence = xpsDocument.GetFixedDocumentSequence();
// ...
这很有效。我可以双击
myPath
上的文件,并在Microsoft XPS Viewer中查看它。如果我将它重命名为ZIP文件,那么我可以在WinZip中打开它

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

File.WriteAllBytes(myPath, myByteArray);
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();