5

在 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
4

3 回答 3

4

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

于 2013-06-20T14:19:28.983 回答
3

NtSetInformationFileFileRenameInformation信息类一起使用。请注意,必须使用 DELETE 访问权限打开句柄。

于 2013-01-22T09:39:33.337 回答
2

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

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

于 2013-01-18T16:34:16.477 回答