1

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.

DaveB
  • 9,470
  • 4
  • 39
  • 66

2 Answers2

2

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;
    }
}
mloar
  • 1,514
  • 11
  • 11
  • Thanks so much. Works great. Took about 33 seconds to check a 621 MB test file on a network share from my workstation. Didn't give any false positives in my testing. – DaveB Apr 17 '12 at 16:24
-2

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

Nudier Mena
  • 3,254
  • 2
  • 22
  • 22
  • 1
    And how do you check that "content Type" ? – H H Apr 13 '12 at 17:17
  • HttpPostedFile.ContentType check PostedFile.ContentType.ToLower() = whaterver mime type you are looking for. I would check on both extension and content type sorry just saw that this is winforms not web – Brian Apr 13 '12 at 17:19
  • take a glance at this article, http://msdn.microsoft.com/en-us/library/ms775147(v=vs.85).aspx#introduction – Nudier Mena Apr 13 '12 at 17:20
  • This is a WinForms app. There is no ContentType to check. There is no uploaded file. – DaveB Apr 13 '12 at 17:23
  • I found this article, but I have not test it yet, http://www.codeproject.com/Articles/6871/Get-a-File-ContentType-from-a-Windows-Forms-App – Nudier Mena Apr 13 '12 at 17:28