如何在Windows上按句柄重命名文件

How to rename a file by handle on Windows?

本文关键字:句柄 重命名 文件 Windows      更新时间:2023-10-16

在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

SetFileInformationByHandle,访问NtSetInformationFile的正确方法,Vista新功能

使用NtSetInformationFile与FileRenameInformation信息类。注意,句柄必须以DELETE权限打开。

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

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