Is there a way to determine whether a file can be opened as a System.IO.Packaging.Package?

188 views Asked by At

If I have a filepath or stream, is there a static method I can use to determine whether the file/stream is a package, other than by trying to use Package.Open on the file/stream and catching the System.IO.FileFormatException?

1

There are 1 answers

0
xxbbcc On BEST ANSWER

You can either attempt to open the file as a .zip file and then look for metadata (thus implementing part of the package specification where you verify the package format) or you can just use Open() and catch any potential exception. (The .docx / .xlsx / etc. formats are just ZIP files that follow a certain structure.)

You can try reading the ZIP header but that will only verify that the file is a ZIP file - I'm not sure this buys you much (if anything).

My guess is that trying to open the file and catching the exception is the easiest route to go - if the specification changes your code will keep working. If you roll your own code to verify the file format, you'll have to keep maintaining it.