i'm trying to find the most generic way to understand if a file is being "used" by any application.
this is true also for applications like notepad/onenote/notepad++ (which don't lock the file).
i'm handling the opening of the files through my app (using Process.Start), and i need to delete the file when the user finishes working on it.
what i managed to come up until now is the following:
- "MSWord like applications" - which has a lock on the file constantly, thus - i know that it's currently being used - and the delete will fail.
- "Notepad/MSPaint like application" - which opens a file in a distinct process, and have a lock on the hosting folder - i can check who's locking the folder, and compare the PID to the PID i received when opening the file
- "OneNote" like applications - which is problematic as when i open the file - i get different PID (i guess that the process opens, and then it sends the file to the single main onenote process). BUT - i can then check it by name and not PID (not the best, but ok) - as i found out onenote also has some kind of lock on the directory. the only issue here is that i'll have to wait until the process is closed, then delete the file.
i'm totally lost about "Notepad++" applications or similar to them. notepad++ doesn't have any lock on the file or folder, and it uses single process. i 'm not sure how to handle this scenario, when doing Process.Start i don't even have a name of the process. (i can check the registry maybe to see who's the default app that opens the file)...
so, any other directions?
thanks!
== EDIT ==
well, currently i've decided about the following logic, unless there's a flaw in it:
- When opening an appliction (Process.Start) - save the PID and the application path. then wait 1 second (or something else i'll think about) - try to get the process by PID - if it exists, this is indeed the PID i want to wait on. if not, then i'll go by process path/name
- check if the file is locked by regular lock (by any application) - if so, then don't delete the file yet.
- if the file is not locked, check who's locking the folder - then compare it to the PID i have. if the PID doesn't exist (and it's indeed the PID i want to wait on) - then delete the file. if it exists - don't delete the file.
- If when starting the process after 1 second the PID doesn't exist, and no lock on the folder/file - i'll just wait until the process ends
that's the idea i think