.net 文件监听类,用于监听指定文件创建与否。
public class DelayFileSystemWatcher
{
private readonly Timer m_Timer;
private readonly Int32 m_TimerInterval;
private readonly FileSystemWatcher m_FileSystemWatcher;
private readonly FileSystemEventHandler m_FileSystemEventHandler;
private readonly Dictionary<String, FileSystemEventArgs> m_ChangedFiles = new Dictionary<string, FileSystemEventArgs>();
public DelayFileSystemWatcher(string path, string filter, FileSystemEventHandler watchHandler, int timerInterval)
{
m_Timer = new Timer(OnTimer, null, Timeout.Infinite, Timeout.Infinite);
m_FileSystemWatcher = new FileSystemWatcher(path, filter);
m_FileSystemWatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.CreationTime;
m_FileSystemWatcher.Created += fileSystemWatcher_Changed;
m_FileSystemWatcher.Changed += fileSystemWatcher_Changed;
//m_FileSystemWatcher.Deleted += fileSystemWatcher_Changed;
//m_FileSystemWatcher.Renamed += fileSystemWatcher_Changed;
m_FileSystemWatcher.EnableRaisingEvents = true;
m_FileSystemEventHandler = watchHandler;
m_TimerInterval = timerInterval;
}
public void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
lock (m_ChangedFiles)
{
if (!m_ChangedFiles.ContainsKey(e.Name))
{
m_ChangedFiles.Add(e.Name, e);
}
}
m_Timer.Change(m_TimerInterval, Timeout.Infinite);
}
private void OnTimer(object state)
{
Dictionary<String, FileSystemEventArgs> tempChangedFiles = new Dictionary<String, FileSystemEventArgs>();
lock (m_ChangedFiles)
{
foreach (KeyValuePair<string, FileSystemEventArgs> changedFile in m_ChangedFiles)
{
tempChangedFiles.Add(changedFile.Key, changedFile.Value);
}
m_ChangedFiles.Clear();
}
foreach (KeyValuePair<string, FileSystemEventArgs> changedFile in tempChangedFiles)
{
m_FileSystemEventHandler(this, changedFile.Value);
}
}
}
调用:
var DelayFileSystemWatcher = new DelayFileSystemWatcher("监听目录, "监听文件名", fileSystemWatcher_Changed, 1500);
private void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
LogManage.Log.Info("监听到文件:" + e.FullPath);
if (!System.IO.File.Exists(e.FullPath))
{
LogManage.Log.Info("文件:" + e.FullPath + "不存在跳过");
return;
}
Oper(e.FullPath);
}