使用打开的句柄删除或重命名文件 [英] Deleting or Renaming a file using an open handle

查看:37
本文介绍了使用打开的句柄删除或重命名文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Windows API 函数 CreateFile 函数允许您指定所需的访问权限.有三个选项 读、写并删除.如果您从 CreateFile 获得请求删除访问权限的句柄,那么您如何使用返回的句柄删除文件?DeleteFile 函数采用文件名,而不是句柄.

The Windows API function CreateFile function allows you to specific the desired access. There are three options read, write and delete. If you get a handle from CreateFile requesting Delete access how do you then delete the file using the returned handle? The DeleteFile function takes the file name, not the handle.

大图:从我的应用程序保存文件时,我首先写出一个临时文件,然后删除真实"文件并将临时文件重命名为真实名称.我已经开始看到搜索索引器或反病毒/间谍软件打开文件进行读取但不允许删除的问题.这会导致我在移动文件时保存失败.我已更改我的打开代码以请求删除访问权限,以确保我可以在需要保存时删除文件.

Big Picture: When saving files from my application I write out to a temporary file first, then delete the "real" file and rename the temporary file to the real name. I have started to see problems with search indexers, or anti virus/spyware opening the file for reading but not allowing deletes. This causes my save to fail when moving the files around. I have changed my open code to request delete access to make sure I can delete the file when it comes time to save.

这一切正常,但我仍然存在第三方应用程序可以获取我的文件的差距.因为我有一个临时文件和真实文件的打开句柄,所以我正在寻找一种使用这些句柄执行删除和重命名功能的方法.我能找到的唯一选择是关闭句柄,然后调用 DeleteFile 和 MoveFile 函数.实际上,我目前正在使用 ReplaceFile API 函数来执行这些步骤,但它也传入了文件名,除非我先关闭句柄,否则将无法工作.

This all works fine but I still have a gap where a third party application could grab my file. Since I have an open handle to both the temporary and real files I was looking for a way to perform the delete and rename functions using those handles. The only option I can find is to close the handles and then call the DeleteFile and MoveFile functions. Actually I am currently using the ReplaceFile API function to perform those steps, but it too has file names passed in and will not work unless I close my handles first.

我仍然需要支持 XP,无法开始使用新的事务文件功能.有没有办法保持文件锁定并仍然删除/重命名它们?

I still need to support XP and cannot start using the new transaction file functions. Is there any way to keep the files locked and still delete/rename them?

推荐答案

在 Windows Vista 中有该功能 SetFileInformationByHandle,可以满足您的需求.

In Windows Vista there is that function SetFileInformationByHandle, that can do what you need.

在以前的 Windows 版本中没有这样的功能,但您拥有等效的本机功能,而不是完全公开的功能 NtSetInformationFile.

In previous versions of Windows there is no such function, but you have the equivalent native, not quite public function NtSetInformationFile.

我没有使用这些功能的经验,也没有 Windows 机器来测试它们,所以我无法向您展示代码,但这应该不难.

I have no experience with these functions, nor a Windows machine to test them, so I cannot show you the code, but that should not be so difficult.

当然,有关本机 Windows 函数的一般免责声明适用.

The general disclaimer about native Windows functions apply, of course.

这篇关于使用打开的句柄删除或重命名文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆