简体   繁体   English

如何确定在Windows下删除文件(文件锁定问题)?

[英]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? 有没有办法删除Windows XP,NTFS文件系统下的文件,即使该文件上有锁?

Having issues with other processes like eg virus scan locking files I want to move/delete. 我想移动/删除其他进程(例如病毒扫描锁定文件)时遇到问题。

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. MoveFileEx允许您传递MOVEFILE_DELAY_UNTIL_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. 如果我没记错的话,可以下载一个名为Open Handles的Microsoft程序,该程序将告诉您哪个进程正在锁定特定文件。 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. 我想如果您要尝试以编程方式而不是手动方式执行此操作,则需要使程序调用oh.exe并相应地处理其输出。 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. 然后使用Windows API(据我所知, TerminateProcess是适当的功能) TerminateProcess相关进程,然后尝试再次删除该文件。

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 ;) 您可以使用一些“尝试计数器”退出循环,以免永远等待;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM