Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' 1.引用類別
Dim watcher As New FileSystemWatcher()
' 2.設定監聽路徑
watcher.Path = "C:\Temp"
' 3.過濾監聽條件
watcher.Filter = "*.txt"
' 4.設定監看類型
watcher.NotifyFilter = NotifyFilters.FileName
' 5.設定監聽項目
AddHandler watcher.Created, AddressOf watcher_Created
' 6.開啟監聽事件
watcher.EnableRaisingEvents = True
End Sub
Private Shared locker As Object = New [Object]()
Private Sub watcher_Created(ByVal sender As Object, ByVal e As FileSystemEventArgs)
SyncLock locker
Dim file As New FileInfo(e.FullPath)
Dim intCounter As Integer = 0
Do While file.IsLocked()
System.Threading.Thread.Sleep(100)
intCounter += 1
If intCounter >= 100 Then Exit Sub
Loop
string readText = file.ReadAllText();
End SyncLock
End Sub
Module clsExtension
<Extension()> _
Public Function IsLocked(ByVal file As FileInfo) As Boolean
Dim stream As FileStream = Nothing
Try
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None)
Catch ex_IsLocked As IOException
'the file is unavailable because it is:
'still being written to
'or being processed by another thread
'or does not exist (has already been processed)
Return True
Finally
If stream IsNot Nothing Then
stream.Close()
End If
End Try
'file is not locked
Return False
End Function
<Extension()> _
Public Function ReadAllText(ByVal file As FileInfo) As String
Try
Using reader As StreamReader = file.OpenText()
Return reader.ReadToEnd()
End Using
Catch ex_ReadAllText As Exception
Return Nothing
End Try
End Function
End Module
參考資料[1] [VB.NET][C#.NET] 使用 FileSystemWatcher 監看資料夾 是否被變更
[2] Wait Until File Is Completely Written






