How do I rename a file using a handle on Windows?
On Windows, how can I rename a file using only its descriptor?
I have no control over how the file is opened (this is done via a proprietary third party library). However, I can get a handle to this file (see # 1).
Also I know that the proprietary library opens a file with the following attributes:
GENERIC_WRITE | GENERIC_READ
and FILE_SHARE_WRITE | FILE_SHARE_READ
.
I tried using a function SetFileInformationByHandle
with a parameter FileRenameInfo
. Unfortunately, this only works if the file was opened with DELETE access, which is not the case here.
Do you have any idea if there is a way to do what I want?
Thanks in advance.
# 1: Note that the library does not provide direct access to the file descriptor. However, it gives me the filename and path. Then I retrieve the handle using the NtQuerySystemInformation and NtQueryObject functions. NtQuerySystemInformation allows me to get a list of all descriptors for the current process (using a value of 16 for the SystemInformationClass parameter), and then I use NtQueryObject to find the exact descriptor the library is opening based on its file path. Therefore, 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
source to share
Use the GetFinalPathNameByHandle API call to get the file name, and then the MoveFile API will rename the file.
But I think you should close this file after you get the file name, or Move / Rename operation will fail
source to share
Use NtSetInformationFile with the FileRenameInformation information class . Note that the handle must be opened with DELETE access.
source to share
SetFileInformationByHandle , the correct way to access NtSetInformationFile, new in Vista.
source to share