Using FileSystemWatcher to Monitor File Creation and Copy It Before Deleting

We have a third party application that writes a file to a directory and then deletes it. We want to copy this file before deleting it.

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);
    }

      

FileSystemWatcher is running. It will see that the file has been created and it goes to OnCreated (). The file is created in the directory.

The only problem is that the file is empty and the file size is 0kb.

I wanted to double check my opinion on why the file is empty. Is it because the file gets deleted so quickly by a third-party application that there is no way for it to make a correct copy? thanks for watching.

+3


source to share


1 answer


Option 1: Instead of looking at the FileSystemWatcher, you should look at how to intercept the code to remove the event. You can watch this comment on Stack Overflow: fooobar.com/questions/2165297 / ...



Option 2: Once your FileSystemWatcher realizes that the file has been created, change the file permission so that it cannot be deleted.

+2


source







All Articles