How to delete a file for sure under windows (problem with file locks)?
is there a way to delete a file under windows xp, ntfs filesystem even if there is a lock on that file?
Having issues with other processes like e.g. virus scan locking files I want to move/de开发者_运维技巧lete.
Thanks for any hints!
MoveFileEx allows you to pass the MOVEFILE_DELAY_UNTIL_REBOOT which will cause the file to be moved/deleted when you next reboot. Other than that, you'd have to find/kill whichever other process(es) currently have the file locked, which may not be possible, and is almost certainly not desirable behaviour for most programs.
If the file is locked when you try to delete it then the deletion will fail. If you need the file to be deleted, then you need whatever is locking it to release the lock.
That's really all there is to it. There are no shortcuts here.
If I recall right, there's a Microsoft program called Open Handles that you can download which will tell you what process is locking a particular file. Then you just kill that process and it unlocks the file so that you can delete it. Doesn't work if the file is locked by a core operating system process, but should work fine if it's locked by a virus scanner.
I guess if you're trying to do this programmatically rather than manually, you'll need to get your program to invoke oh.exe and process its output accordingly. Then kill the relevant process using the Windows API (to the best of my knowledge, TerminateProcess
is the appropriate function) and try deleting the file again.
If you absolutely need to delete the file before proceeding, you may do following:
#include <stdio.h>
...
while(remove("myfile.txt" ) != 0)
// Error deleting file. Wait a little before trying again.
Sleep(100);
After the loop you absolutely sure that file is successfully deleted.
You may use some "attempts counter" to exit the loop to not wait forever ;)
精彩评论