0

Watching the filesystem with FileSystemWatcher. When a file is deleted I want to get the last write date of that file.

Do I have to sample a baseline of all files monitored when my script starts or can this be done without?

Or am I using the wrong tool?

  • At the risk of being obvious, you can't get attributes of a deleted file, since it no longer exists. You would have to watch for all changes and cache the last write time of all files as they fly by (but even then it's possible you'll [miss some](https://stackoverflow.com/q/9563037/4137916), since the file system doesn't update this synchronously -- in theory it's possible that a file is written to and deleted without any observer seeing the write, though I don't know how NTFS actually behaves there). – Jeroen Mostert Feb 07 '23 at 14:32
  • I know that the file is already gone when the event fires. But maybe I can get the info from the event details or something? – stackedyellowangel Feb 07 '23 at 15:39
  • Try it and see. I very much doubt this ever happens, and if it does, it won't consistently happen, because it must basically be true that both the last write time changes *and* the file is deleted. This is either not possible (depending on the implementation) or not probable. – Jeroen Mostert Feb 07 '23 at 16:11
  • Thank you for you reply! I will describe what's happening: Several files get replaced from time to time (every few weeks) If the replaced file is older than the replacing file everything is fine. Nothing to do. But if the replaced file is newer than the replacing file I need to do something (open an incident rerquest) The files wil not be changed only replaced. I see the delete-create-sequence. But I don't know what the previous Last Write Date was. I could save this in a file/table though. I am just wondering if I could avoid this. – stackedyellowangel Feb 09 '23 at 09:29
  • As `FileSystemWatcher` is notoriously unreliable (or rather, it's hard to use in a reliable way, and the system delivers changes on a best-effort basis only) I would personally never rely on *only* `FileSystemWatcher`, and if immediate action is not required, I wouldn't rely on it at all, as opposed to periodic snapshots for comparison. – Jeroen Mostert Feb 09 '23 at 10:13
  • If possible, you can also look into changing the way files are copied/transferred; for example, `robocopy` can be configured to only replace older files, and you can parse its output to see if a copy was skipped due to the file being newer. An ounce of prevention is worth a pound of cure, as they say. – Jeroen Mostert Feb 09 '23 at 10:21

0 Answers0