Neil Weicher
Neil Weicher

Reputation: 2502

Deleting a file with just a handle

Lets say I have a file handle as a result of WinAPI CreateFile. It was not opened with FILE_FLAG_DELETE_ON_CLOSE.

Is there a way to delete the file having just the handle, without having the file name?

Thanks

Upvotes: 0

Views: 1352

Answers (3)

NuSkooler
NuSkooler

Reputation: 5525

Vista+ provides GetFinalPathNameByHandle() which can be used with VOLUME_NAME_DOS to query the "DOS" path which you can then pass to DeleteFile().

Upvotes: 0

Bukes
Bukes

Reputation: 3718

If you're running on Windows Vista or greater, SetFileInformationByHandle() will allow you to do this by setting information class FileDispositionInfo.

The net result of this operation will be that the handle will now be marked for delete on close - when the last handle to the file is closed, the file will be deleted.

For older versions of Windows, NTDLL exports NtSetInformationFile() that'll let you do the same thing.

Upvotes: 4

Marty
Marty

Reputation: 7522

I don't know if you can specifically delete the file based solely on the handle, but you could always use the handle to retrieve the file name, as described in this MSDN article, and then call DeleteFile().

Upvotes: 1

Related Questions