我的FileSystemWatcher沒有拋出任何事件。我已經看過這些類似的問題,似乎沒有一個答案是我的問題:FileSystemWatcher不觸發事件
*編輯:我的目標是捕獲何時將XLS文件複製到或創建在目錄中。
- Filesystemwatcher doesn't trigger event
- FileSystemWatcher - event not firing the second time
- FileSystemWatcher Changed event doesn't fire
- FileSystemWatcher - only the change event once firing once?
Monitor類:
public class Monitor
{
FileSystemWatcher watcher = new FileSystemWatcher();
readonly string bookedPath = @"\\SomeServer\SomeFolder\";
public delegate void FileDroppedEvent(string FullPath);
public event FileDroppedEvent FileDropped;
public delegate void ErrorEvent(Exception ex);
public event ErrorEvent Error;
public Monitor()
{
watcher.Path = bookedPath;
watcher.Filter = "*.xls";
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.Error += new ErrorEventHandler(watcher_Error);
}
void watcher_Error(object sender, ErrorEventArgs e)
{
Error(e.GetException());
}
void watcher_Changed(object sender, FileSystemEventArgs e)
{
if (e.ChangeType != WatcherChangeTypes.Created) return;
FileDropped(e.FullPath);
}
public void Start()
{
watcher.EnableRaisingEvents = true;
}
public void Stop()
{
watcher.EnableRaisingEvents = false;
}
}
簡單的形式與列表框:
public partial class Form1 : Form
{
Monitor monitor = new Monitor();
public Form1()
{
InitializeComponent();
FormClosing += new FormClosingEventHandler(Form1_FormClosing);
Load += new EventHandler(Form1_Load);
monitor.FileDropped += new Monitor.FileDroppedEvent(monitor_FileDropped);
monitor.Error += new Monitor.ErrorEvent(monitor_Error);
}
void Form1_Load(object sender, EventArgs e)
{
monitor.Start();
}
void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
monitor.Stop();
}
void monitor_Error(Exception ex)
{
listBox1.Items.Add(ex.Message);
}
void monitor_FileDropped(string FullPath)
{
listBox1.Items.Add(FullPath);
}
}
我在做什麼錯?
用戶代碼是否可以訪問網絡路徑運行? – adrianbanks
是的。我正在運行它,我有權訪問 – DontFretBrett
您可能會發現以下線程有用:http://stackoverflow.com/questions/11219373/filesystemwatcher-to-watch-unc-path – Edin