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

Day*_*yan 9 vb.net visual-studio-2010 winforms

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

目前使用System.IO和以下代码命名的类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
Run Code Online (Sandbox Code Playgroud)

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

Jer*_*son 15

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
Run Code Online (Sandbox Code Playgroud)

  • 好的解决方案 我只想补充一点,你需要确保stream.close()以防万一没有异常,所以程序可以继续没有问题. (2认同)
  • @CaryBondoc`Imports System.Runtime.InteropServices;`修复*Marshal未声明*问题.**提示:**'Marshal`将有一个蓝色的小下划线,将鼠标悬停在此上,它会给你一个关于错误的提示! (2认同)
  • `调用IsFileOpen(new FileInfo(filePath))` (2认同)

jus*_*sij 6

使用'is file in use check'功能确实没有意义,因为您仍然需要尝试catch来处理文件无法打开的情况.打开文件可能会失败的原因多于它刚刚打开的原因.

使用功能进行检查也不能保证成功."正在使用中的文件检查"可能仅对文件已打开错误的文件打开时返回false,因为在检查和尝试打开文件之间的时间是由其他人打开的.

  • 应该是一个评论,而不是一个答案 (2认同)