2025年9月17日 星期三

VB.NET 檔案是否被鎖定

 參考引用:VB.NET 檔案是否被鎖定

--

Try                

    Dim fs AsFileStream = NewFileStream(excelFileName, FileMode.OpenOrCreate, FileAccess.Read)

              fs.Close()

Catch ex AsException

     MessageBox.Show(excelFileName & "文件当前已经打开,请先关闭")            

     Return   '  退出        

End  Try


----


Imports System.IO

Imports System.Runtime.InteropServices


Public Class Form1


    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        Dim str_thispath As String = String.Empty '完整檔案路徑

        str_thispath = TextBox1.Text

        TextBox2.Text = ""

        If File.Exists(str_thispath) Then

            IsFileOpen(str_thispath)

        Else

            TextBox2.Text = "檔案不存在:" & Date.Now.ToString("yyyy/MM/dd HH:mm:ss.fffffff") & " 結束執行。" & vbNewLine & TextBox2.Text

        End If

        TextBox2.Text = "系統於 " & Date.Now.ToString("yyyy/MM/dd HH:mm:ss.fffffff") & " 結束執行。" & vbNewLine & TextBox2.Text

    End Sub


    Function IsFileOpen(ByVal str_thispath As String) As Boolean

        Dim stream As FileStream = Nothing

        Try

            stream = File.Open(str_thispath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)

            stream.Close()

            TextBox2.Text = "檔案可開啟:" & Date.Now.ToString("yyyy/MM/dd HH:mm:ss.fffffff") & " " & vbNewLine & TextBox2.Text

        Catch ex As Exception


            If TypeOf ex Is IOException AndAlso IsFileLocked(ex) Then

                TextBox2.Text = "發生例外錯誤:原因可能檔案正在使用中已上鎖..." & Date.Now.ToString("yyyy/MM/dd HH:mm:ss.fffffff") & " " & vbNewLine & TextBox2.Text

                Return True

            End If

        End Try

        Return False

    End Function


    Function IsFileLocked(exception As Exception) As Boolean

        Dim ERROR_SHARING_VIOLATION As Integer = 32, ERROR_LOCK_VIOLATION As Integer = 33

        Dim errorCode As Integer = Marshal.GetHRForException(exception) And ((1 << 16) - 1)

        Return errorCode = ERROR_SHARING_VIOLATION OrElse errorCode = ERROR_LOCK_VIOLATION

    End Function


End Class

沒有留言:

張貼留言