Imports System.Runtime.InteropServices
Imports Microsoft.Office.Core
Imports Word = Microsoft.Office.Interop.Word
Public Class Form1
Private Function IsDocProtected(ByVal filename As String) As Boolean
Dim wordApp As Word.Application = Nothing
Dim doc As Word.Document = Nothing
Dim isProtected As Boolean = False
Try
wordApp = New Word.Application
open: readonly, open/write password = "Wibble", show word = false
doc = wordApp.Documents.Open(filename, True, , , "Wibble", , , "Wibble", , , , False)
doc.Close(False)
Catch ex As System.Runtime.InteropServices.COMException
wrong password error:
If ex.ErrorCode = &H800A1520 Then isProtected = True
Finally
GC.Collect()
GC.WaitForPendingFinalizers()
wordApp.Quit()
Dim referenceCount As Integer = 0
Do
referenceCount = Marshal.ReleaseComObject(wordApp)
Loop Until referenceCount < 1
wordApp = Nothing
End Try
Return isProtected
End Function
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ofd As New OpenFileDialog
ofd.Title = "Select office document to open"
Dim result As Windows.Forms.DialogResult
result = ofd.ShowDialog
If result = Windows.Forms.DialogResult.OK Then
If ofd.FileName IsNot Nothing Then
Me.Text = IsDocProtected(ofd.FileName)
End If
End If
End Sub
End Class