How dou detect if a file is being access by a process


I am downloading a file from an ftp server and move it afterwards to a separate folder. But I am getting this error: The process cannot access the file because it is being used by another process. I am thinking that file-download was not yet finished when the move was done. How do I know if a file is being access or not by any process?
Who is Participating?
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
I think he means programmatically check...   =)

Attempt to open the file with exclusive access...if it fails then someone else has it open.

See IO.FileShare.None:

            Dim fs As New System.IO.FileStream("c:\someFile.txt", IO.FileMode.Open, IO.FileAccess.ReadWrite, IO.FileShare.None)

            ' do something with "fs" have exclusive access to it
            ' and NO one else has it open (or can open it while you are working with it)

        Catch ex As Exception
            ' could not get read/write lock, file IS in use by someone else
        End Try

You could use a Timer and attempt again after a couple seconds if it fails.
You can use the sysinternals tool filemon...

The explanation/use is in the link.
Idle_Mind -

I think you are right!! ;)   FAIL!  Didn't mind the zone - sorry.
JaimeJegoniaAuthor Commented:

I already have that function but it seems that my code is still able to move the file because I can see files with size 0kb on the destination folder. When I put a delay before moving, it worked. But I'm afraid that this approach would result to a bottleneck later. Any suggestions?

Here's the code:
    Public Function IsLock(ByVal filenameAs String) As Boolean
        Dim result As Boolean = False
        Dim fs As System.IO.FileStream

            fs = System.IO.File.Open(filenameAs , IO.FileMode.OpenOrCreate, IO.FileAccess.Read, IO.FileShare.None)
        Catch ex As System.IO.IOException
            result = True
        End Try

        Return result
    End Function
Mike TomlinsonMiddle School Assistant TeacherCommented:
The difference may be that you are using IO.FileAccess.Read instead of IO.FileAccess.ReadWrite.  You are saying, "open this file for reading and don't allow any other processes to read it at the same time".

The other process isn't reading (it's just writing) so it might not throw the error...?
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.