Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename a file by handle on Windows?

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
like image 591
ben Avatar asked Jan 18 '13 16:01

ben


3 Answers

SetFileInformationByHandle, the proper way to access NtSetInformationFile, new in Vista .

like image 185
Bruno Martinez Avatar answered Oct 11 '22 23:10

Bruno Martinez


Use NtSetInformationFile with FileRenameInformation info class. Note that the handle must be opened with DELETE access.

like image 39
Sergey Podobry Avatar answered Oct 11 '22 22:10

Sergey Podobry


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

like image 2
Antonio Bakula Avatar answered Oct 11 '22 21:10

Antonio Bakula