检查文件夹中的新文件
我需要监视一个文件夹以查看何时创建新文件,然后处理该文件并将其存档。检查文件夹中的新文件
它的实际检测新文件,我正在努力...我明白,我需要在看FileSystemWatcher的东西,但想知道是否有人知道它的用法的任何例子,以这种方式让我开始了吗?
说我的文件夹是“C:\ Temp \”,我需要知道任何带有“.dat”扩展名的文件。
对不起,模糊的问题,我只是没有能够找到我正在寻找与各种谷歌搜索。
在此先感谢
您可以使用FileSystemWatcher Class此:它侦听文件系统更改通知,并当目录或文件目录中,变化引发事件。
Imports System
Imports System.IO
Imports System.Diagnostics
Public watchfolder As FileSystemWatcher
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
watchfolder = New System.IO.FileSystemWatcher()
watchfolder.Path = "d:\pdf_record\"
watchfolder.NotifyFilter = IO.NotifyFilters.DirectoryName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
IO.NotifyFilters.FileName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
IO.NotifyFilters.Attributes
AddHandler watchfolder.Changed, AddressOf logchange
AddHandler watchfolder.Created, AddressOf logchange
AddHandler watchfolder.Deleted, AddressOf logchange
AddHandler watchfolder.Renamed, AddressOf logrename
watchfolder.EnableRaisingEvents = True
End Sub
Private Sub logchange(ByVal source As Object, ByVal e As _
System.IO.FileSystemEventArgs)
If e.ChangeType = IO.WatcherChangeTypes.Changed Then
MsgBox("File " & e.FullPath & _
" has been modified" & vbCrLf)
End If
If e.ChangeType = IO.WatcherChangeTypes.Created Then
MsgBox("File " & e.FullPath & _
" has been created" & vbCrLf)
End If
If e.ChangeType = IO.WatcherChangeTypes.Deleted Then
MsgBox("File " & e.FullPath & _
" has been deleted" & vbCrLf)
End If
End Sub
Public Sub logrename(ByVal source As Object, ByVal e As _
System.IO.RenamedEventArgs)
MsgBox("File" & e.OldName & _
" has been renamed to " & e.Name & vbCrLf)
End Sub
所以我设法得到这个工作,我怎么想和揣摩柜面同样的事情后,有人是有史以来我会分享它。
使用本指南[http://www.dreamincode.net/forums/topic/150149-using-filesystemwatcher-in-vbnet/]作为参考,我在表单中添加了FileSystemWatcher组件。
我用下面的硬编码目录我想监控:
Public Sub agent_Shown(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Shown
Fsw1.Path = "C:\temp"
End Sub
我使用以下方法来添加创建一个列表框的文件的完整路径...
Private Sub fsw1_Created(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles Fsw1.Created
listbox_PendingJobs.Items.Add(e.FullPath.ToString)
End Sub
这按照检测文件夹中的新文件的方式工作。 现在,我要放下一个后台工作人员,以5分钟的时间间隔通过计时器启动并处理列表框中的条目(如果找到)。
您很可能在使用此代码时遇到问题。您的FileSystemWatcher运行在与UI不同的线程上,因此当您引用ListBox时,事情可能会分崩离析。你需要设置'SynchronizingObject'属性来避免它。 – Plutonix 2014-09-24 16:32:57
由于您所做的只是从MSDN复制代码,您可能已*至少*修改它以更准确地应用于OP的问题。 – Plutonix 2014-09-24 12:33:21
感谢Neethu Soman,但这些似乎正在寻找命令行参数。如果可能,我想对目录进行硬编码。 你知道我会如何修改上述内容吗? 谢谢! – John 2014-09-24 13:07:17
现在试试这个更新的代码,我出去了。 – 2014-09-24 13:20:37