开发者

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. (And I already tried and confirmed this via 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

The DeleteFile function fails if an application attempts to delete a file that is open for normal I/O or as a memory-map开发者_如何学Cped file.

Is there any other way to delete a file that is open, but does not have the FILE_SHARE_DELETE flag set?


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.


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). 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. 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. But this requres using code injection techniques. I don't know how it can be done easier.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜