Q

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

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

Dig deeper on Service-oriented architecture (SOA) implementations

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

0 comments

Oldest 

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:

SearchSoftwareQuality

SearchCloudApplications

SearchAWS

TheServerSide

SearchWinDevelopment

Close