Private m_WatchDirectory As String Private WithEvents m_FileSystemWatcher As FileSystemWatcherPrivate 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
用这个可以监视目录和文件
Private WithEvents m_FileSystemWatcher As FileSystemWatcherPrivate 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