(ZipPackage)myWordDocument

Fun fact: MSOffice 2013+ documents are compressed archives, a.k.a. zip files. They’re built and manipulated using the same System.IO.Packaging namespace that’s used by¬†SQL Server Data Tools to make dacpacs.

Advertisements

Copy an Open Word/Excel File

I had a requirement to disallow saving a file over a certain size. Simple! Wait…how do I find out what size it is without saving it?

Make a copy of the file and check the size of the copy. Wait…I want to check the size of the in-memory edits. Curses! Foiled again.

Luckily, the Excel object model has the answer: Workbook.SaveAsCopy. This method does exactly what I want. So:

  1. Get a temporary file path.
  2. .SaveAsCopy.
  3. Check the size of the copy.
  4. Delete the copy.

And now we copy & paste for Word…which doesn’t have that method.

!

But a Word Document does implement the IPersistFile interface, which implements the Save method, which is the same thing. So cast your Document to IPersistFile and save away.

So now I’ve got all the pieces.

  1. Intercept the save.
  2. Copy the in-memory document.
  3. Check the size.
  4. Delete the copy.
  5. Warn the user that the document is too large.
  6. Don’t save.
  7. Happy dance.