|
|
Title | Use the FileSystemWatcher class to process files placed in a directory in VB .NET |
Description | This example shows how to use the FileSystemWatcher class to process files placed in a directory in VB .NET. When the FileSystemWatcher receives a Created event, the program processes the file and deletes it. |
Keywords | FileSystemWatcher, VB.NET |
Categories | VB.NET, Files and Directories |
|
|
When the program loads, it creates a FileSystemWatcher to watch for changes in the Files directory. It then calls subroutine ProcessExistingFiles. That routine loops through the files currently in the directory and calls ProcessFile for each.
When the FileSystemWatcher receives a Created event, its event handler calls ProcessFile for the new file.
Subroutine ProcessFile simply lists the file and deletes it. A real application would probably do something else with the file.
|
|
Private m_WatchDirectory As String
Private WithEvents m_FileSystemWatcher As FileSystemWatcher
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
e As System.EventArgs) Handles MyBase.Load
lstFiles.Items.Add(Now.ToString() & " Starting")
' Get the path to the directory we will watch.
m_WatchDirectory = Application.StartupPath
m_WatchDirectory = m_WatchDirectory.Substring(0, _
m_WatchDirectory.LastIndexOf("\"))
m_WatchDirectory &= "\Files"
' Make the FileSystemWatcher.
m_FileSystemWatcher = New _
FileSystemWatcher(m_WatchDirectory, "*.txt")
m_FileSystemWatcher.NotifyFilter = 0
m_FileSystemWatcher.NotifyFilter = _
m_FileSystemWatcher.NotifyFilter Or _
NotifyFilters.FileName
m_FileSystemWatcher.EnableRaisingEvents = True
' Process any files that already exist.
ProcessExistingFiles(m_WatchDirectory)
End Sub
' Process a new file.
Private Sub m_FileSystemWatcher_Created(ByVal sender As _
Object, ByVal e As System.IO.FileSystemEventArgs) _
Handles m_FileSystemWatcher.Created
ProcessFile(e.FullPath)
End Sub
' Process existing files.
Private Sub ProcessExistingFiles(ByVal directory_name As _
String)
Dim dir_info As New DirectoryInfo(directory_name)
Dim file_infos As FileInfo() = dir_info.GetFiles()
For Each fi As FileInfo In file_infos
ProcessFile(fi.FullName)
Next fi
End Sub
' Process a file.
Private Sub ProcessFile(ByVal file_name As String)
lstFiles.Items.Add(Now.ToString() & " Processed " & _
file_name)
File.Delete(file_name)
End Sub
|
|
|
|
|
|