[英]Is it possible to delete a file that is opened by a process under windows?
For testing and simulation purposes I would like to delete a file that is currently open by my process. 为了进行测试和模拟,我想删除当前由进程打开的文件。
The CreateFile docs state that it is possible to open a file in a mode ( FILE_SHARE_DELETE
) that allows the file the open handle is pointing to to be deleted by another operation. CreateFile文档指出,可以以一种模式(
FILE_SHARE_DELETE
)打开文件,该模式允许打开句柄指向的文件被另一个操作删除。 (And I already tried and confirmed this via CreateFile(FILE_SHARE_DELETE) + DeleteFile.) (并且我已经尝试过并通过CreateFile(FILE_SHARE_DELETE)+ DeleteFile确认这一点。)
What I would like to know now however is, whether it is possible at all that a file that is opened by anyone without above mentioned flag to be deleted somehow? 但是,我现在想知道的是,是否有可能以某种方式删除没有上述标志的任何人打开的文件?
As far as I understand the DeleteFile docs it would not be possible with this functions, as 据我了解DeleteFile文档 ,此功能将是不可能的,因为
The DeleteFile function fails if an application attempts to delete a file that is open for normal I/O or as a memory-mapped file.
如果应用程序尝试删除为常规I / O打开或作为内存映射文件打开的文件,则DeleteFile函数将失败。
Is there any other way to delete a file that is open, but does not have the FILE_SHARE_DELETE flag set? 还有其他方法可以删除已打开但未设置FILE_SHARE_DELETE标志的文件吗?
There is no way to do this. 没有办法做到这一点。
The closest way to do something like this is to schedule delete on reboot using MoveFileEx with a target filename of NULL
, and MOVEFILE_DELAY_UNTIL_REBOOT
in the dwFlags
parameter. 执行此操作的最接近方法是使用目标文件名为
NULL
MoveFileEx并在dwFlags
参数中使用MOVEFILE_DELAY_UNTIL_REBOOT
计划重新启动时进行删除。
I don't think there's a legitimate way to delete such a file. 我认为没有删除此类文件的合法方法。 However, if you'd like to be bullet proof, bare in mind that there are tools that can close your handle from the outside, and then the file can be easily deleted ( Process Explorer is one such tool, but there are others ).
但是,如果您想防弹,请记住,有些工具可以从外面关闭手柄,然后可以轻松删除文件( Process Explorer是这样的一种工具,但还有其他工具)。 If someone closes the handle of a file you've opened, you'll get an error trying to use that handle.
如果有人关闭您打开的文件的句柄,则尝试使用该句柄时会出现错误。
You can look at DeleteFileTransacted , it allows to mark the file for deletion on close. 您可以查看DeleteFileTransacted ,它允许在关闭时标记要删除的文件。 But it doesn't fit you if you want to delete file immediately.
但是,如果要立即删除文件,则不适合您。 If file has no
FILE_SHARE_DELETE
flag you need to close it first, but for this purpose you need to get file handle and then close it. 如果文件没有
FILE_SHARE_DELETE
标志,则需要先将其关闭,但是为此,您需要获取文件句柄然后将其关闭。 But this requres using code injection techniques. 但这需要使用代码注入技术。 I don't know how it can be done easier.
我不知道该如何轻松完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.