我有,我用FileSystemWatcher的和移動文件從一個destiantion到另一個被創建時就簡單C#控制檯應用。我的代碼如下所示:File.Move()會自動關閉控制檯窗口在C#
public static void WatchForFiles()
{
FileSystemWatcher watcher = new FileSystemWatcher();
//folder path is path to folder
watcher.Path = folderPath;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
//Add event handlers
watcher.Created += new FileSystemEventHandler(File_OnChanged);
//Begin watching
watcher.EnableRaisingEvents = true;
}
public static void File_OnChanged(object sender, FileSystemEventArgs e)
{
//destiantion path is path to folder
string destiantionFileFullPath = destianationPath + e.Name;
if (!File.Exists(destiantionFileFullPath))
{
File.Move(e.FullPath, destiantionFileFullPath);
}
}
當我第一次複製文件時,它正常移動。但之後或者如果我複製兩個或多個文件,我的控制檯窗口會自動關閉。我想我應該使用IAsyncResult但我不知道如何。我試過任務但這並沒有幫助。冷杉複製文件,然後刪除也沒有幫助。這是什麼原因造成的?我怎樣才能防止這種情況?在此先感謝
聽起來像是你有一個異常的地方拋出。創建一個bat文件,在其中調用窗口控制檯程序,然後暫停。 – GETah
從內存中我相信FileWatcher可能會在文件完全寫入磁盤之前通知您一個新文件(因此您可能試圖移動一個仍然被鎖定以便寫入的文件)。在File.Move和WriteLine中添加一個try {} catch塊,這是控制檯的例外情況 - 這可能會幫助您解決問題的底部。 – KazR
當我使用try catch時,一切正常,沒有異常拋出,這很奇怪 –