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