title: How to rename a file by handle on Windows?
body: <p>On Windows, how can I rename a file using only its handle?</p>
  
  <p>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).</p>
  
  <p>Also I know that the proprietary library opens the file with the following attributes:</p>
  
  <p><code>GENERIC_WRITE | GENERIC_READ</code> and <code>FILE_SHARE_WRITE | FILE_SHARE_READ</code>.</p>
  
  <p>I have tried using the <code>SetFileInformationByHandle</code> function with <code>FileRenameInfo</code> as parameter. Unfortunately this seems to work only if the file was opened with the DELETE access type which is not the case here.</p>
  
  <p>Do you have any ideas if there is a way to do what I want?</p>
  
  <p>Thanks in advance.</p>
  
  <p>#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.</p>
  
  <pre><code>/* 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
  </code></pre>