更新时间:2023-09-20 13:49:58
它只能用作延迟操作,使用 MOVEFILE_DELAY_UNTIL_REBOOT
flag 。这是一个特权操作,需要用户上下文来启用管理员令牌( UAC )。这是安装程序在使用时如何替换文件,然后他们要求操作员重新启动系统。
正如您所看到的,不是微不足道的,你应该尝试避免这样做。
Using Windows API, is it possible to rename a file that's open in another process without FILE_SHARE_DELETE
permissions?
I thought it's impossible based on CreateFile
docs that say:
Note: Delete access allows both delete and rename operations.
Consistent with that, renaming through regular rename
in the end-user command prompt, I often encountered The process cannot access the file because it is being used by another process.
; a similar error happens with renaming through end-user GUI and through python's os.rename
.
However, this highly-upvoted answer seems to state the opposite:
Deleting will fail if any other process has the file opened without delete sharing, renaming is never a problem.
And it's not just a minor point; the entire answer depends on that statement: it only solves the OP problem if renaming wouldn't fail when delete would.
What am I missing?
Note: If it matters, I am referring to Windows 10, using C++ API (which I assume is strictly more powerful than C# API).
Edit: moved the code snippet to a new question.
It is only possible as a deferred operation, using the MOVEFILE_DELAY_UNTIL_REBOOT
flag. It is a priviledged operation that requires the user context to enable the Administrator token (UAC). This is how installers replace a file while in use, and then they ask for the operator to reboot the system.
As you can see, is not trivial and you should try to avoid doing this.