Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

windows - How to rename a file without closing all of it's open file handles?

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);  

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

this is how I do it :

MoveFileA(aFileName, aNewFileName);

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...