感謝所有幫助這個..FileSystemWatcher的線程上
我試圖寫一個小程序FileWatcher監視本地目錄和副本跨越到另一個本地目錄中的任何改變。我在.Net中使用了FileSystemWatcher類,在我的btnStart中單擊我運行四個線程,每個線程都有自己的FileSysWatcher實例,用於監視不同的更改類型。所以我想要尋找的第一個是創建的事件。
new Thread(Created).Start();
那麼我:
void Created()
{
FileSystemWatcher Watcher2 = new FileSystemWatcher();
Watcher2.Path = txtBxDirToWatch.Text;
Watcher2.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.DirectoryName;
//watch all files in the path
Watcher2.Filter = "*.*";
//dont watch sub dir as default
Watcher2.IncludeSubdirectories = false;
if (chkBxIncSub.Checked)
{
Watcher2.IncludeSubdirectories = true;
}
Watcher2.Created += new FileSystemEventHandler(OnCreated);
Watcher2.EnableRaisingEvents = true;
}
所有我想這個做的就是複製到一個硬編碼的本地路徑的任何變化,但我不能得到任何結果。這裏是我處理事件的地方
public static void OnCreated(object source, FileSystemEventArgs e)
{
//combine new path into a string
string created = Path.Combine(@"C:\WatcherChanges", e.Name);
File.Create(created);
}
您是否嘗試調試它?你的OnCreated是否被打到,然後你創建文件?你確定e.Name是一個文件名,而不是完整的文件路徑嗎? – Nikolay 2012-03-29 06:05:10
檢查是否創建了此新線程,因爲您正在從新線程訪問UI控件。我相信這是拋出異常,你沒有看到它。 – Marcin 2012-03-29 06:15:12