Question System.IO.File.OpenRead still reads a file even when its in use?

skibunny

New member
Joined
Jan 15, 2010
Messages
2
Programming Experience
1-3
Hi,

I have a function to check if a file is open:

Public Shared Function IsFileOpen(ByVal fileItem As String, ByRef bFileStatus As Boolean) As Boolean
Try
Dim stream As FileStream = System.IO.File.OpenRead(fileItem)
stream.Close()
bFileStatus = False
Catch
bFileStatus = True
End Try
Return bFileStatus
End Function

I need to check whether a file is open so that an alert can be put on screen for the user to close it before continuing to the next stage of the application.

But when I test the function with a file open, the error is not being caught.

Can anyone help please?
 
Even if a file is open somewhere it still may allow others various access, your code checks if the file can be read. Have a look at this IO.File.Open method File.Open Method (String, FileMode, FileAccess, FileShare) (System.IO) Here you can give different parameters for the type of access and share you require for the file. FileAccess is the kind of access you need, FileShare is what access you allow other processes that try to open file while you use it.
 
Thanks

Thanks, I changed my function to:

Public Shared Function IsFileOpen(ByVal fileItem As String) As Boolean
Dim nFileNum As Integer
nFileNum = FreeFile()
Try
FileOpen(nFileNum, fileItem, OpenMode.Binary, OpenAccess.Read)
FileClose(nFileNum)
Return False
Catch
Return True
End Try
End Function

This appears to return the correct result when a file is opened.
 
This code does nothing differently than the other code, it internally opens a FileStream with the same parameter options you have with IO.File. The only difference is that File.OpenRead specifies FileShare.Read while FileOpen (binary,read) sets FileShare.None. Since FileShare determines what could happen after the file has been opened, ie with subsequent opens, the difference in detecting whether file is open is none.
 
Back
Top