Telling if an app has a file locked

  • Thread starter Thread starter Smokey Grindle
  • Start date Start date
S

Smokey Grindle

I need a way to tell if a program such as word or excel has a document it
locked (open for editing). Is there any way to do this in VB.NET? All I need
is a its open for editing or not response thats all... thanks!
 
I guess one way to do it is like this, is this the best way though?

''' <summary>

''' Check if a file is locked or open for editing

''' </summary>

''' <param name="filePath"></param>

''' <returns></returns>

''' <remarks></remarks>

Public Shared Function ISFileLockedForWriting(ByVal filePath As String) As
Boolean

Dim result As Boolean = False

Try

Using fs As System.IO.Stream = IO.File.Open(filePath, IO.FileMode.Open,
IO.FileAccess.Write, IO.FileShare.None)

fs.Close()

result = False

End Using

Catch ex As Exception

result = True

End Try

Return result

End Function
 
afaik its the only way without delving deep into the guts of windoze. Its a
pain when I'm debugging, because a perfectly valid program action has to
result in a thrown exception but you know, can't have everything (like a
simple locked status bit for instance).

One thing I would note, you should be careful you know exactly why it failed
in the exception handler (handle IOException instead) - it might fail due to
filenotfound (a bug for instance) or some other reason not related to
locking.
 
Back
Top