Ask the Expert

Is there a way to tell if a file is password-protected without opening it? (part 2)

I wrote a batch program which opens and changes MS Word and Excel files. However, if an input file is password protected, the password dialog comes up and my program is stuck. Can you tell me how to either find if a file is password protected without opening it, or how to open it so that it will just fail, without bringing the dialog?

    Requires Free Membership to View

Click here to read part one of this answer.

Sub Main()

Dim Stg As Storage
Dim PropSetStg As PropertySetStorage
Dim PropStg As PropertyStorage

Dim theFilename As String
Dim theMessage As String
theMessage = "ON"
theFilename = "c:test.xls"

' The steps are first to attach to the file creating a
' storage object. Then you retrieve the property set
' collection and from that the specific property set that
' you are interested in. In our case, the password protection
' information is in the summary information. Once we have
' fetched this information, we retrieve the specific item
' that we are interested in. The property is 0 when the
' file is not password protected and 1 when it is.

' Create our objects and fetch our info
Stg = New Storage(theFilename)
PropSetStg = Stg.PropertySetStorage()
PropStg = PropSetStg.Open(PropSetStg.FMTID_SummaryInformation)

' Test the result. Here we set a simple message as the action.
If PropStg(SummaryProperty.DocSecurity) = 0 Then
theMessage = "OFF"
End If

Stg.Close()
PropSetStg.Close()

Console.WriteLine("Password protection for """ & theFilename & """ is " & theMessage & ".")

' For debugging. Wait for user to hit CR before letting the
' letting the app terminate.
Console.ReadLine()

End Sub

If you want more information about structured storage you can visit the following links.

MSDN information on structured storage

VB unsupported utility object from Microsoft (Dsofile.exe self installer)

C++ code sample
 

This was first published in December 2002

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: