如何使用C#检查文件是有效的XPS文件? [英] How Can I Check That A File Is A Valid XPS File With C#?

查看:73
本文介绍了如何使用C#检查文件是有效的XPS文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a WinForms application that processes XPS files. How can I check that the file the user has selected in the open dialog is a valid XPS file using C#?

将存在带有.XPS扩展名的文件,这些文件不是真正的XPS文件.

There WILL be files present with the .XPS extension that are not really XPS files.

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

Since XPS files are really in the PKZIP format, I could check for the PKZIP byte signature but that would give false positives on ZIP archives.

推荐答案

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

The following will distinguish XPS files from other ZIP archives and non-ZIP files. It won't determine whether the file is fully-valid XPS - for that you would need to load each page.

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;
    }
}

这篇关于如何使用C#检查文件是有效的XPS文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆