On Windows, how can I rename a file using only its handle?
I do not control how the file is opened (it is done through a proprietary third-party library). However I can retrieve a handle to this file (See #1).
Also I know that the proprietary library opens the file with the following attributes:
GENERIC_WRITE | GENERIC_READ
and FILE_SHARE_WRITE | FILE_SHARE_READ
.
I have tried using the SetFileInformationByHandle
function with FileRenameInfo
as parameter. Unfortunately this seems to work only if the file was opened with the DELETE access type which is not the case here.
Do you have any ideas if there is a way to do what I want?
Thanks in advance.
#1: Note that the library does not give direct access to the file handle. However it gives me the file name and path. I then retrieve the handle using the NtQuerySystemInformation and NtQueryObject functions. NtQuerySystemInformation allows me to retrieve the list of all handles for the current process (using value 16 for the SystemInformationClass parameter), and then I use NtQueryObject to find the exact handle opens by the library based on its filepath. So I am not opening a separate handle.
/* Here is a basic pseudo-code demonstrating what I am trying to achieve */
library::Initialize(); //This creates a new file with a random name. The library keeps a handle opens internally until we call library::close.
file_info_struct tFileInfo;
library::GetFileInfo(tFileInfo); //This gives me information about the created file
HANDLE hFile = my::GetHandleFromFilePath(tFileInfo.file_path); //This function uses NtQuerySystemInformation and NtQueryObject functions to retrieve the existing handle
my::RenameFileByHandle(hFile, someNewFileName); //This is what I am missing. I do not know how to rename the file using its handle
//Carry on with using the library
....
library::close(); //This will close the internal file handle
SetFileInformationByHandle, the proper way to access NtSetInformationFile, new in Vista .
Use NtSetInformationFile with FileRenameInformation info class. Note that the handle must be opened with DELETE access.
Use API call GetFinalPathNameByHandle to get file name and then with MoveFile API rename the file.
But I think that you should close that file after you get the file name or Move / Rename operation will fail
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With