My users like to upload password-protected Word documents into our custom document management system. I'd like to add a validation to check for the password and refuse the upload if it has a password.
Automating Word - with COM interop - is out of the question because this is a server side application.
net: Detect if a docx is password protected to open file: msgbox(documentName. haspassword. tostring) This will give you true or false for the password protection.
Click File > Options. Click Trust Center > Trust Center Settings > Protected View.
Microsoft Office 2007: To encrypt files in Microsoft Office 2007 first open your Word document or Excel spreadsheet. Then click the Office button in the top left corner of your window and choose “Prepare”. Now click “Encrypt Document” and enter the desired password when prompted.
Add a password to Microsoft Office First, open the Office document you would like to protect. Click the File menu, select the Info tab, and then select the Protect Document button. Click Encrypt with Password. Enter your password then click OK.
I think it is going to depend on the version of Microsoft Word. Older versions of Word (before 2007) will require some COM interop, because they are not saved in an open format. Nothing you can do to get around that, and I feel your frustrations with installing anything Office on a web server. Additionally, I believe the only way to detect password protection on these is to attempt to open/unprotect the file and catch a certain exception (you may have to further evaluate an error code within the exception as well). Not pretty!
However, for newer versions of word (2007+) saved in the open DOCX format (Standard ECMA-376), you can examine the XML and check for the existence of the DocumentProtection
element with the w:enforcement
attribute set to "on"...
<w:DocumentProtection
w:edit="read-only"
w:enforcement="on"
w:unprotectPassword="1FC6CBEB"/>
Note: The password seen here is encrypted (obviously); I saved this particular document with a password of "test".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With