了解 VB.NET 中的 Open 方法和 Try 块

Understanding the Open method and the Try block in VB.NET

我是第一次使用VB.NET,检查文件是否在使用中,但有些代码行我不完全理解。

有人可以解释下面在评论中突出显示的两行代码吗?

Public Sub Main()
    IsFileInUse("C:\someFolder\file.pdf")
End Sub


Function IsFileInUse(filePath As String) As Boolean
    IsFileInUse = False
    If System.IO.File.Exists(filePath) Then
        Dim fileInfo As System.IO.FileInfo
        Dim stream As System.IO.FileStream
        fileInfo = New System.IO.FileInfo(filePath)
        Try
            ' Can someone explain this line of code?
            ' how does this determines where to go from here, Catch or Finally?
            stream = fileInfo.Open(System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None)
        Catch
            IsFileInUse = True
            MessageBox.Show("It looks like the file is opened")
        Finally
            If stream IsNot Nothing Then
                ' What is this closing?
                stream.Close()
            End If
        End Try
    Else 
        MessageBox.Show("File does NOT Exist")
    End If
End Function

how does this determines where to go from here, Catch or Finally?

看看documentation for FileInfo.Open。异常部分显示了所有可能发生的异常。

如果抛出异常,将执行Catch块。

无论是否抛出异常,Finally 块都会被执行。

What is this closing?

它将释放流的资源,在这种情况下它将关闭文件。

Try 块 运行 是代码。在 Try 块中,流用于打开文件并访问其内容。如果该代码由于任何原因出错,它将抛出异常,然后导致 Catch 块为 运行。代码的 Finally 块将 运行 是否抛出异常。在 Finally 块中,正在关闭到文件的流。

该代码正在通过尝试以 read/write 访问权限打开文件来确定该文件当前是否被任何其他进程 "in use"。无论打开文件是否失败,它总是关闭文件流。它假设如果以该模式打开文件由于任何原因失败,那么一定是因为它是 "in use"。这是一个糟糕的假设,而且可能不是实现它的最佳方式,但就其价值而言,这就是它正在做的事情。

Try/Catch 块是 VB.NET 用于异常处理的首选语法(它取代了早于 .NET 的旧 On Error 语法)。当 Try 部分内的任何内容抛出异常时,执行将跳转到 Catch 部分。一旦 Catch 部分执行完成,它就会跳转到 Finally 部分。如果 Try 部分没有抛出异常,那么一旦完成,它也会跳转到 Finally 部分。本质上,Finally 部分中的所有内容都是 "guaranteed" 执行,无论是否发生异常,而 Catch 部分中的代码仅在出现异常时执行。

换句话说,考虑这个例子:

' Outputs "ABCE" (does not output "D")
Console.Write("A")
Try
    Console.Write("B")
    Console.Write("C")
Catch
    Console.Write("D")
Finally
Console.Write("E")

并将其与此示例进行比较:

' Outputs "ABDE" (does not output "C")
Console.Write("A")
Try
    Console.Write("B")
    Throw New Exception()
    Console.Write("C")
Catch
    Console.Write("D")
Finally
Console.Write("E")

有关该主题的更多信息,请参阅 the MSDN article