Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!!

like image 328
Dayan Avatar asked Jul 02 '12 03:07

Dayan


2 Answers

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.

like image 196
jussij Avatar answered Oct 27 '22 10:10

jussij


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))
like image 42
Jeremy Thompson Avatar answered Oct 27 '22 09:10

Jeremy Thompson