簡體   English   中英

如何使用C#檢查文件是有效的XPS文件?

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

我有一個處理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;
    }
}

您可以檢查文件的內容類型,而不是文件擴展名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM