File sitting on a network drive is still open by another applicati

G

Guest

How can I detect if a file sitting on a network drive is still open by another
application?

This application resides on another machine on the network?

I am using VB.NET 2003

Your help is highly appreciated
 
J

Joris De Groote

Try to open it, if you cant open it, it's still in use.
You could write a try catch around this and eventually write some loop to
test periodically if you can open it, and when you can, you could use the
file?


"Moumen VB.NET 2003/2005 Developer"
 
G

Guest

Hi,

I tried your approach, but with no success.

Could you please post some code on how you can do it?

Thanks
 
R

Robin Mark Tucker

I would write something like:


' Precondition: the file "theFile" is known to exist

Public Function IsLocked(ByVal theFile As String) As Boolean

Dim theStream As FileStream
Dim theResult As Boolean

Try

' To test if the file is locked, it is enough just to try and open
it and handle
' any (resulting) exception. If an exception is raised, then the
file is locked.

theStream = New FileStream(theFile, FileMode.Open, FileAccess.Write)

' Success

theResult = False

Catch ex As IOException

' We failed to open it for writing, so it's probably locked.

theResult = True

Finally

If Not theStream Is Nothing Then
theStream.Close()
End If

End Try

Return theResult

End Function





"Moumen VB.NET 2003/2005 Developer"
 
J

Joris De Groote

Yep

And if you want to wait until you want to open it, you can stil write a
while loop around it and keep trying until theResult = false .

Greetz
 
G

Guest

Joris & Robin,

Thank you very much for your valuable replies.

However, I noticed that when I try to open a text file through NotePad.exe,
my program cannot detect that the file is open for writing by NotePad. On the
other hand, if I open the same text file with MS-Word, my program works
perfectly.

I would like my program to work with any application that tries to open the
network file.

Do you know why this happening only with NotePad?

Thanks!
 
J

Joris De Groote

I don't know this for sure (but this is what I think)
I don't think Notepad locks a file (since its pretty much a very basic
program), MS-Word does.

Joris

"Moumen VB.NET 2003/2005 Developer"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top