VB :: Code & APIs

[VB.NET] 파일 시스템 감시하기

VB.NET 에서는 파일 시스템을 감시 할 수 있는 클래스를 제공합니다.

Form에 Button 과 Label 을 삽입하신 이후, Button 의 Click Event 와 Delegate 등을 설정하여 줍니다.

Button 을 클릭한 다음 C:\ 아래에 *.txt 파일을 만들거나, 삭제하거나, 변경하면 Label 에 내용을 표시해 줍니다.

멀티쓰레딩을 지원하기 위하여 Delegate 를 설정하였습니다.


'// FileWatcher 를 사용하기 위한 네임스페이스를 선언합니다.

Imports System.IO

'// 멀티쓰레드 환경에서 안전하게 실행하기 위한 코드입니다.

Delegate Sub SetTextCallback(ByVal [text] As String)

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

'// 감시 대상은 C:\ 전체입니다.

Dim fsw As New FileSystemWatcher("C:\")

'// *.txt 파일을 주 감시 대상으로 합니다.

fsw.Filter = "*.txt"

fsw.NotifyFilter = (NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName)

AddHandler fsw.Changed, New FileSystemEventHandler(AddressOf OnChanged)

AddHandler fsw.Created, AddressOf OnChanged

AddHandler fsw.Deleted, AddressOf OnChanged

'// 감시를 시작합니다.

fsw.EnableRaisingEvents = True

End Sub

Private Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs)

SetText("File: " & e.FullPath & " " & e.ChangeType)

End Sub

Private Sub SetText(ByVal [text] As String)

If lblWat.InvokeRequired Then

Dim d As New SetTextCallback(AddressOf SetText)

Me.Invoke(d, New Object() {[text]})

Else

label.Text = [text]

End If

End Sub

Leave a Reply

Discover more from Dream big, Achieve more.

Subscribe now to keep reading and get access to the full archive.

Continue reading