I'm using a FileWatcher to trigger processing of files as soon as they are added to a folder. After the file it is processed i开发者_JS百科t is deleted.
My problem is that after the file is deleted I get another file change event which is so close to the deletion than in some cases checking for File.Exists it tells that the file still exists. But of course some milliseconds later when looking to process the file it does not really exists. The FileWatcher is set to notify on NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.Attributes
Thanks, florin
If you take a little search on SO, you'll find plenty of questions, where people like to check if they are able to access a file or if they have the rights needed.
The problem is, that even if you check it (like you do with File.Exists()
) the situation can be changed when it comes to the real operation.
So just throw out the File.Exists()
and put a try catch
around your deletion operation.
If it fails, it's up to you to decide if you just drop it silently, inform the user, close your application, shutdown the pc, etc.
usually filewatcher fires multiple times since the fileChange is a series of events. Here is a useful link. http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx Scroll to the end.
Save to say, it's been a while since this was asked, but seeing as I asked myself, if the change event will indeed be triggered when a file is deleted I thought I might as well chip in an answer.
To prevent your OnChange event from following through, you can check the FileSystemEventArgs for the WatcherChangeType and simply return, on a deleted event.
private static void OnChanged(object sender, FileSystemEventArgs e)
{
if (e.ChangeType == WatcherChangeTypes.Deleted)
{
return;
}
Console.WriteLine($"Changed: {e.FullPath}");
}
精彩评论