I am trying to detect when a file is being removed from a folder in my drive. Upon detection, I want to write code that does something. Is there an event handler for this kind of 'event' in C#? Looked around but couldn't find any. Is it even possible?
Asked
Active
Viewed 76 times
2
-
1Filesystemwatcher will do the job. Look here for a similar topic [link](https://stackoverflow.com/questions/239988/filesystemwatcher-vs-polling-to-watch-for-file-changes) – jannowitz Aug 12 '19 at 22:15
1 Answers
1
You can use FileSystemWatcher to monitor a directory, and subscribe to it's Deleted
event. See the code below
static void Main(string[] args)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "C:/some/directory/to/watch";
watcher.NotifyFilter = NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.FileName |
NotifyFilters.DirectoryName;
watcher.Filter = "*.*";
watcher.Deleted += new FileSystemEventHandler(OnDeleted);
watcher.EnableRaisingEvents = true;
}
private static void OnDeleted(object sender, FileSystemEventArgs e)
{
throw new NotImplementedException();
}

Lukas
- 498
- 2
- 12