As Richie says, catching an exception is probably the best approach here.
But what if you want to delete 10 files and you do not want it to fail halfway? You really need some way to protect the overall transaction. Therefore, it is useful to be able to passively check if a file is being used. You can determine if a file is being used (or read-only, which also makes it invulnerable) by simply trying to open it for writing (and then, if you succeed, close it immediately). This alone does not guarantee that a subsequent uninstall attempt will succeed.
Other approaches that might work would be: - move / rename the file before deleting (put them in a safe place so that you know that they cannot be opened by another process later), so that you can "cancel" the transaction, if any of the individual move operations fail. - catch the exception and queue for a future attempt to delete the file (either in your own program, or you can mark the file to automatically delete Windows at the next reboot)
source share