VB.NET在继续读/写之前检查文件是否打开?

有没有方法来验证文件是否已打开?我唯一能想到的是Try / Catch,看看我是否可以捕获文件打开异常,但我发现如果文件打开,我可以使用一个方法返回true / false.

目前在名为Wallet的类下使用System.IO和以下代码.

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

任何指针将不胜感激!谢谢!!

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

相关文章

Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强...
VB6或者ASP 格式化时间为 MM/dd/yyyy 格式,竟然没有好的办...
在项目中添加如下代码:新建窗口来显示异常信息。 Namespace...
转了这一篇文章,原来一直想用C#做k3的插件开发,vb没有C#用...
Sub 分列() ‘以空格为分隔符,连续空格只算1个。对所选...
  窗体代码 1 Private Sub Text1_OLEDragDrop(Data As Dat...