How Can I Check That A File Is A Valid XPS File With C#?

早过忘川 提交于 2019-11-28 10:42:11

问题


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#?

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

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.


回答1:


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



回答2:


You can check for the content Type of the file instead of the file extension.



来源:https://stackoverflow.com/questions/10145247/how-can-i-check-that-a-file-is-a-valid-xps-file-with-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!