Hallo!
Kleines Beispiel-Formular
Public Class frmFilesystemViewer
Dim WithEvents fsw As New IO.FileSystemWatcher
Dim fbd As New FolderBrowserDialog With {.ShowNewFolderButton = False}
Dim dt As New DataTable
Dim bs As New BindingSource
Dim dgv As New DataGridView With
{.Parent = Me, .Top = 50, .Left = 10, .Width = 300, .Height = 400, _
.DataSource = bs}
Dim WithEvents btnFolderToWatch As New Button With
{.Parent = Me, .Top = 5, .Left = 5, .Width = 300, .Text = "Folder To Watch" & _
"Files"}
Private Sub frmFilesystemViewer_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
With dt.Columns
.Add("Name", GetType(String))
.Add("Size", GetType(Integer))
.Add("Creation", GetType(Date))
End With
dt.PrimaryKey = {dt.Columns("Name")}
bs.DataSource = dt
End Sub
Private Sub btnFolderToWatch_Click(sender As Object, e As EventArgs) _
Handles btnFolderToWatch.Click
If fbd.ShowDialog = DialogResult.Cancel Then Exit Sub
FillTable(fbd.SelectedPath)
With fsw
.Filter = "*.*"
.NotifyFilter = IO.NotifyFilters.FileName Or _
IO.NotifyFilters.LastWrite
.Path = fbd.SelectedPath
.EnableRaisingEvents = True
End With
End Sub
Private Function FillTable(ByVal folder As String) As Integer
bs.SuspendBinding()
With dt.Rows
.Clear()
Dim di As New IO.DirectoryInfo(folder)
For Each fi As IO.FileInfo In di.GetFiles("*.*")
Dim row As DataRow = dt.NewRow
row("Name") = fi.Name : row("Size") = fi.Length
row("Creation") = fi.CreationTime
.Add(row)
Next fi
Return .Count
End With
bs.ResumeBinding()
bs.ResetBindings(False)
End Function
Private Function Reset()
bs.ResetBindings(False)
End Function
Private Sub fsw_Renamed(sender As Object, e As IO.RenamedEventArgs) Handles _
fsw.Renamed
Dim row As DataRow = dt.Rows.Find(e.OldName)
row("Name") = e.Name
Invoke(New MethodInvoker(AddressOf Reset))
End Sub
Private Sub fsw_Deleted(sender As Object, e As IO.FileSystemEventArgs) _
Handles fsw.Deleted
Dim row As DataRow = dt.Rows.Find(e.Name)
dt.Rows.Remove(row)
Invoke(New MethodInvoker(AddressOf Reset))
End Sub
Private Sub fsw_Created(sender As Object, e As IO.FileSystemEventArgs) _
Handles fsw.Created
Dim fi As New IO.FileInfo(e.FullPath)
Dim row As DataRow = dt.NewRow
row.ItemArray = {fi.Name, fi.Length, fi.CreationTime}
dt.Rows.Add(row)
Invoke(New MethodInvoker(AddressOf Reset))
End Sub
Private Sub fsw_Changed(sender As Object, e As IO.FileSystemEventArgs) _
Handles fsw.Changed
If e.ChangeType = IO.WatcherChangeTypes.Changed Then
Dim row As DataRow = dt.Rows.Find(e.Name)
Dim fi As New IO.FileInfo(e.FullPath)
row.ItemArray = {fi.Name, fi.Length, fi.CreationTime}
End If
Invoke(New MethodInvoker(AddressOf Reset))
End Sub
End Class |