3

I've been trying to set an error trap that will detect if a file is already open. This is no problem when the file is a text file using the following code:

Private Function FILEOPEN(ByVal sFile As String) As Boolean

    Dim THISFILEOPEN As Boolean = False
    Try
        Using f As New IO.FileStream(sFile, IO.FileMode.Open)
            THISFILEOPEN = False
        End Using
    Catch
        THISFILEOPEN = True
    End Try
    Return THISFILEOPEN
End Function

My problem is that when the file is an open JPG file, not a text file, the above function returns False indicating that it is not open? I have tried different variations of the function but still cannot find a function that can tell if a JPG file is open.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • see if this helps http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use – mmeasor Aug 15 '14 at 18:17

1 Answers1

4

You should NOT do this kind of behavior. Simple answer is because after you check, but before you do anything with it, the file may become unavailable. A proper way is to handle an exception as you access the file. You may find this answer helpful:

Community
  • 1
  • 1
Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151