如何使用C#检查文件是否为有效的XPS文件?

我有一个处理XPS文件的WinForms应用程序。 如何检查用户在打开的对话框中选择的文件是否是使用C#的有效XPS文件?

将有.XPS扩展名的文件不是真正的XPS文件。

由于XPS文件实际上是PKZIP格式,我可以检查PKZIP字节签名,但这会给ZIP存档带来误报。

以下内容将XPS文件与其他ZIP存档和非ZIP文件区分开来。 它不会确定文件是否是完全有效的XPS – 因为您需要加载每个页面。

using System; using System.IO; using System.Windows.Xps.Packaging; class Tester { public static bool IsXps(string filename) { try { XpsDocument x = new XpsDocument(filename, FileAccess.Read); IXpsFixedDocumentSequenceReader fdsr = x.FixedDocumentSequenceReader; // Needed to actually try to find the FixedDocumentSequence Uri uri = fdsr.Uri; return true; } catch (Exception) { } return false; } } 

您可以检查文件的内容类型而不是文件扩展名。