Problem solve Get help with specific problems with your technologies, process and projects.

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?

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


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

' For debugging. Wait for user to hit CR before letting the
' letting the app terminate.

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

Dig Deeper on Topics Archive

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.