如何在不关闭所有打开文件句柄的情况下重命名文件? [英] How to rename a file without closing all of it's open file handles?

查看:199
本文介绍了如何在不关闭所有打开文件句柄的情况下重命名文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 createFile 创建 GENERIC_READ 文件句柄.这是我的指示:

I create GENERIC_READ file handle with createFile. This is my instruction :

   hfile :=  CreateFileA(aFileName,  
                         GENERIC_READ,  
                         FILE_SHARE_READ or 
                           FILE_SHARE_WRITE,  
                         nil,  
                         OPEN_EXISTING,  
                         FILE_ATTRIBUTE_NORMAL or 
                           FILE_FLAG_SEQUENTIAL_SCAN or 
                             FILE_FLAG_OVERLAPPED, 
                         0);  

现在的问题是,何时处理将通过 hfile 读取文件,有时另一个进程将需要交换"文件,并且为此需要重命名

Now the problem is that when to process will read the file via hfile sometime another process will need to "swap" the file, and to do this will need to rename it

这就是我的方法:

MoveFileA(aFileName, aNewFileName);

但是当他们仍然打开某些文件句柄时,执行此操作时出现错误.他们有什么方法可以重命名文件而无需先关闭其所有GENERIC_READ文件句柄?

But I have an error when I do this when their is still some file handle open. Is their any way to rename a file without first closing all it's GENERIC_READ file handle?

推荐答案

显然,首选选择是确保每次打开文件时,都会传递 FILE_SHARE_DELETE 标志.

Obviously the preferred choice is to ensure that every time the file is opened, the FILE_SHARE_DELETE flag is passed.

如果您无法执行此操作(例如,您无法控制的其他进程可能会打开它),剩下的替代方法是将 MoveFileEx MOVEFILE_DELAY_UNTIL_REBOOT 一起使用旗帜.正如您从名称中猜测的那样,它会等到下次计算机重新启动时再重新命名.对于诸如服务之类的东西所使用的文件,该文件特别有用,该文件会在服务启动后立即将其打开,并保持打开状态,直到系统关闭为止.

If you can't do that (e.g., some other process over which you have no control may open it) the remaining alternative is to use MoveFileEx with the MOVEFILE_DELAY_UNTIL_REBOOT flag. As you'd guess from the name, this waits until the next time the computer is restarted, and renames it then. This is particularly useful for files that are used by something like a service that opens them as soon as the service starts, and keeps them open until the system is shut down.

这确实有其自身的局限性.例如,您不能使用它通过网络共享来重命名文件.重命名是在启动过程的早期公平地完成的,然后重新连接持久网络共享.

This does have some limitations of its own though. For one example, you can't use it to rename a file via a network share. The renaming is done fairly early in the boot process, before persistent network shares are re-connected.

这篇关于如何在不关闭所有打开文件句柄的情况下重命名文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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