3

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-mapped file.

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

1
  • Under some circumstances it can be renamed. This is useful in you want to upgrade/replace it Commented Dec 1, 2010 at 11:15

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

3 Comments

Also keep in mind that handle values can be recycled, so very strange things can happen (at least in theory) if you do this. Use it as a last resort when trouble-shooting something, not as part of production code.
@Leo Davidson - yes, I know... I tried to find Raymond Chen's post about that, but just couldn't locate it, so I left this note out. Have you by any chance read it? Would love to add the link, for future reference.
I was thinking of the same article but I can't find it either. :(
1

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.

1 Comment

Same problem as before, I think. "The DeleteFileTransacted function fails if an application attempts to delete a file that is open for normal I/O or as a memory-mapped file."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.