Dayan
Dayan

Reputation: 8031

VB.NET Checking if a File is Open before proceeding with a Read/Write?

Is there a method to verify that a file is open? The only thing I can think of is the Try/Catch to see if i can catch the file-open exception but I figured that a method be available to return true/false if file is open.

Currently using System.IO and the following code under class named Wallet.

    Private holdPath As String = "defaultLog.txt"
    Private _file As New FileStream(holdPath, FileMode.OpenOrCreate, FileAccess.ReadWrite)
    Private file As New StreamWriter(_file)

    Public Function Check(ByVal CheckNumber As Integer, ByVal CheckAmount As Decimal) As Decimal
        Try
            file.WriteLine("testing")
            file.Close()
        Catch e As IOException
          'Note sure if this is the proper way.
        End Try

        Return 0D
    End Function

Any pointers will be appreciated! Thank you!!

Upvotes: 9

Views: 65032

Answers (3)

Jeremy Thompson
Jeremy Thompson

Reputation: 65692

Private Sub IsFileOpen(ByVal file As FileInfo)
    Dim stream As FileStream = Nothing
    Try
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None)
        stream.Close()
    Catch ex As Exception

        If TypeOf ex Is IOException AndAlso IsFileLocked(ex) Then
            ' do something here, either close the file if you have a handle, show a msgbox, retry  or as a last resort terminate the process - which could cause corruption and lose data
        End If
    End Try
End Sub

Private Shared Function IsFileLocked(exception As Exception) As Boolean
    Dim errorCode As Integer = Marshal.GetHRForException(exception) And ((1 << 16) - 1)
    Return errorCode = 32 OrElse errorCode = 33
End Function

Call it like this:

Call IsFileOpen(new FileInfo(filePath))

Upvotes: 18

Mark Hall
Mark Hall

Reputation: 54552

It looks like the two suggestions from this MSDN forum posting both involve trying to open the file.

The first one is similar to what you are doing now, and the second involves using a Windows API function (CreateFile) and checking for a invalid handle signifying the file is in use. In both cases they are relying on an error condition to determine if the file is open or not. In short, in my opinion the method you are using is correct since there is not a System.IO.File.IsOpen property.

Upvotes: 2

jussij
jussij

Reputation: 10580

There is really no point using a 'is file in use check' function since you will still need to have try catch to handle the case that the file fails to open. The file open can fail for many more reasons than it just being already open.

Also using a function to do a check is no guarantee of success. The 'is file in use check' might return false only for the file open to fail with a file already open error, because in time between the check and trying to open the file it was opened by someone else.

Upvotes: 6

Related Questions