2016-03-28 124 views
0

我想檢查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而不是功能。

此致敬禮。

+0

你爲什麼喜歡Sub over Function?如果你想檢查文件是否被打開,函數會更好,因爲你可以使它返回True或False,因此你可以在'If'語句中檢查它。 –

+0

我建議你將返回類型修改爲'Boolean',並在函數的最後一行返回'True',並在'Catch'塊中返回False。我也認爲'FileStream'會比'StreamWriter'更好。 –

+0

@VisualVincent您可以發佈您建議的代碼嗎? – Markowitz

回答

0

若要使用此代碼,您需要使用的功能,如下面的例子:

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 

功能,OpenUnlockedFile(「C:\ Data.xlsb」)運行時,只要按下Button1的(在此例)。如果該函數運行並且它返回Nothing,那麼您將知道該文件已被鎖定。

請注意,您還需要

Imports System.IO 

在這個例子中工作。

+0

這並沒有告訴他它是否被打開,實際上它什麼都不做,除非你像'If'語句那樣檢查它。 –

+0

我也看到了,並在幾分鐘前做了編輯! – Dustin

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 

請注意,無論是功能只會告訴你,如果該文件是可訪問的,它可能是一個進程打開它不鎖定它。

相關問題