【问题标题】:Is there a way I can check to see if the file is already open?有没有办法检查文件是否已经打开?
【发布时间】:2016-07-15 13:06:56
【问题描述】:

我想检查 C:\Data.xlsb 是否已经打开。

我从这里得到以下代码How to tell if a certain Excel file is open using VB.NET?

Public Shared Function OpenUnlockedFile(ByVal path As String) As StreamWriter
Dim sw As StreamWriter = nothing
Try
    sw = New StreamWriter(path)
Catch ex As IOException When System.Runtime.InteropServices.Marshal.GetLastWin32Error() = 32
    REM locked, return nothing
End Try
Return sw
End Function

但我不知道如何使用上面的代码。

我更喜欢 sub 而不是函数。

最好的问候。

【问题讨论】:

  • 为什么你更喜欢 Sub 而不是函数?如果你想检查文件是否打开,函数会更好,因为你可以让它返回 True 或 False,因此你可以在 If-statement 中检查它。
  • 我建议您将返回类型修改为Boolean,并在函数的最后一行返回True,并在Catch 块中返回False。我也认为FileStream 会比StreamWriter 更好。
  • @VisualVincent 你能发布你建议的代码吗?
  • 当然,给我几秒钟...

标签: .net vb.net excel file streamwriter


【解决方案1】:

您应该将返回类型更改为Boolean 以更好地满足您的需求,并且还应该从StreamWriter 切换到FileStream。这是因为在您链接的帖子中,OP 想要写入文件,我认为您不需要(或者至少不使用纯文本 StreamWriter)。

Public Shared Function IsFileAvailable(ByVal path As String) As Boolean
    Try
        Dim fs As New FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None)
        fs.Close()
    Catch ex As IOException When System.Runtime.InteropServices.Marshal.GetLastWin32Error() = 32
        Return False
    End Try
    Return True
End Function

那么你就可以这样使用它:

If IsFileAvailable("C:\Data.xlsb") = True Then
    'File is not locked, do what you like here.
Else
    MessageBox.Show("The file is locked!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If

请注意,任何一个函数都只会告诉您文件是否可访问,有可能是某个进程在未锁定的情况下打开了它。

【讨论】:

    【解决方案2】:

    要使用此代码,您可以使用以下示例中的函数:

    Imports System.IO
    
    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            If OpenUnlockedFile("C:\Data.xlsb") Is Nothing Then
                MessageBox.Show("File is locked")
            End If
        End Sub
    
        Public Shared Function OpenUnlockedFile(ByVal path As String) As StreamWriter
            Dim sw As StreamWriter = Nothing
            Try
                sw = New StreamWriter(path)
            Catch ex As IOException When System.Runtime.InteropServices.Marshal.GetLastWin32Error() = 32
            REM locked, return nothing
            End Try
            Return sw
        End Function
    
    End Class
    

    只要按下 Button1(在本例中),就会运行函数 OpenUnlockedFile("C:\Data.xlsb")。如果函数运行并返回 Nothing,那么您将知道文件已被锁定。

    请注意,您还需要

    Imports System.IO
    

    为了让这个例子起作用。

    【讨论】:

    • 这并不能告诉他它是否打开,实际上它什么也不做,除非你像If-statement 一样检查它。
    • 我也看到了,并在几分钟前进行了编辑!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    相关资源
    最近更新 更多