如何在 Windows 上通过句柄重命名文件?

ben*_*ben 5 c++ windows winapi

在 Windows 上,如何仅使用文件句柄重命名文件?

我不控制文件的打开方式(它是通过专有的第三方库完成的)。但是我可以检索这个文件的句柄(见#1)。

我也知道专有库打开具有以下属性的文件:

GENERIC_WRITE | GENERIC_READFILE_SHARE_WRITE | FILE_SHARE_READ

我曾尝试使用该SetFileInformationByHandle函数FileRenameInfo作为参数。不幸的是,这似乎只有在使用 DELETE 访问类型打开文件时才有效,而此处并非如此。

如果有办法做我想做的事,你有什么想法吗?

提前致谢。

#1:请注意,该库不提供对文件句柄的直接访问。但是它给了我文件名和路径。然后我使用 NtQuerySystemInformation 和 NtQueryObject 函数检索句柄。NtQuerySystemInformation 允许我检索当前进程的所有句柄列表(使用 SystemInformationClass 参数的值 16),然后我使用 NtQueryObject 根据其文件路径查找库打开的确切句柄。所以我没有打开一个单独的句柄。

/* 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
Run Code Online (Sandbox Code Playgroud)

Ant*_*ula 2

使用 API 调用GetFinalPathNameByHandle获取文件名,然后使用MoveFile API 重命名文件。

但我认为您应该在获取文件名后关闭该文件,否则移动/重命名操作将失败

  • 只要打开的文件位于同一驱动器上,即使它被锁定,移动它也会成功。 (3认同)
  • 好吧,我认为这是不可能的,因为如果文件已打开,MoveFile 将失败 (2认同)