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

前端 未结 3 1005
臣服心动
臣服心动 2020-12-01 19:31

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 tha

3条回答
  •  孤街浪徒
    2020-12-01 19:54

    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
    

提交回复
热议问题