Reputation: 4905
I am writing a desktop application under Windows in C++ MFC.
The application creates a index file, and writes information to it again and again.
If the application crashes, the next time the application starts it will delete the crashed index file and create a new one. I think in certain cases, the index file will be locked. It will be a disaster if I can not delete the locked index file.
How can I guarantee that I can delete the file and create a new one? I can make sure no other application opens the index file. It cannot be deleted just because of an application crash.
Can any one help?
Upvotes: 2
Views: 2660
Reputation: 196
For a one-off solution, boot into safe mode and delete it. I had a .exe on my C: drive get locked while I was building it in a compiler, and nothing could remove it including a reboot. However, in Safe Mode I could delete it.
Upvotes: 0
Reputation: 77
I can recommend using this tool: http://lockhunter.com/download.htm
It helped me to unlock my Skype account on Windows 8 by being able to delete '%appdata%/Skype/my-user-profile' while other tools and procedures did not help in my case (ref. to "another skype instance may exist", which bites a lot of other users also since long).
Upvotes: 0
Reputation: 34421
Sometimes it's possible to rename a locked file. You should probably fix the real problem rather than the symptom, though.
Upvotes: 0
Reputation: 99685
To unlock file you should close all handles associated with it. The best way to do it is to terminate crashed application that still running (and owns file handle).
To find crashed application you could use technique that described in this article. That is what Process Explorer does when you search handles of files with specified name.
Upvotes: 3
Reputation: 929
Most likely the answer is "you cannot delete a locked file". The OS won't let you.
Instead I would work around it with something like this.
Bonus credit: allow users to "recover" a crashed index file instead of deleting them automatically.
Upvotes: 0
Reputation: 281795
If there's no process keeping the file open, there's no way it can remain locked. You might find that as long as your crashed process does actually die (rather than hanging) you have no problem.
If you really do need to be sure that you can delete the file from one process while another process has it open, you need both processes to open it with the FILE_SHARE_DELETE
flag.
Upvotes: 7