Reputation: 319
We have a 3rd party application that writes a file to a directory and then deletes it. We want to copy that file before it is deleted.
We have this:
FileSystemWatcher watcher;
private void WatchForFileDrop()
{
watcher = new FileSystemWatcher();
watcher.Path = "c:\\FileDrop";
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName;
watcher.Filter = "*.txt";
watcher.Created += new FileSystemEventHandler(OnCreated);
watcher.EnableRaisingEvents = true;
}
private void OnCreated(object source, FileSystemEventArgs e)
{
//Copy the file to the file drop location
System.IO.File.Copy(e.FullPath, "C:\\FileDropCopy\\" + e.Name);
}
The FileSystemWatcher does work. It will see that the file has been created and it goes to the OnCreated(). The file is created in the directory.
The only problem is the file is empty and the file size is 0kb.
I wanted to double check my thinking of why the file is empty. Is it because the file is deleted so quickly by the 3rd party application that it doesn't have the chance to do a proper copy? thanks for taking a look.
Upvotes: 3
Views: 5997
Reputation: 1442
Options 1: Instead of looking at FileSystemWatcher, you should look to hook your code to delete event. You can look this this comment on Stack Overflow: https://stackoverflow.com/a/4395147/442470
Option 2: As soon as your FileSystemWatcher realizes that a file is created, change permission of the file so that it cannot be deleted.
Upvotes: 2