Windows:覆盖正在使用的文件
我正在尝试编写一个实用程序,允许在 Windows 中移动文件,并且当它发现正在使用的文件时,将设置该文件在重新启动时移动。
看来 MoveFileEx (http://msdn.microsoft. com/en-us/library/aa365240(VS.85).aspx) 是正确的调用,但是我无法弄清楚我正在从 GetLastError (http://msdn.microsoft.com/en-us/library/ms679360(VS .85).aspx) 以查看该文件是否正在使用。
我希望该实用程序在出现实际权限问题时失败。 有没有办法区分“你不能在那里写”和“使用中的覆盖错误”?
另外,如果我将要移动的文件放在用户的临时文件夹中,它们会在延迟重命名之前被删除吗?
I am trying to write a utility that will allow moving files in Windows, and when it finds a file in use, will set that file to be moved on reboot.
It seems that MoveFileEx (http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx) is the right call for this, however I cannot figure out what error code I'm looking for from GetLastError (http://msdn.microsoft.com/en-us/library/ms679360(VS.85).aspx) to see that the file was in use.
I want the utility to fail when there is an actual permissions problem. Is there anyway to differentiate a you-can't-write-there and a in-use overwrite error?
Also, if I have the files I am moving in the user's temporary folder, will they get deleted before the delayed rename?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须首先调用 CreateFile 看看是否该文件正在使用中。
查看文件是否正在使用:
如果您获得有效的文件句柄,那么您就知道该文件与已打开该文件的进程没有冲突的共享权限。
如果您指定不共享访问(CreateFile 调用的 dwShareMode 参数为 0),那么如果任何其他进程当前正在以任何方式使用该文件,您将不会获得文件句柄。 在这种情况下,GetLastError 将返回:
ERROR_SHARING_VIOLATION (32)
要查看访问该文件是否存在安全问题:
要查看访问该文件是否存在权限问题, CreateFile 调用也会失败,但会出现不同的 GetLastError。 您将收到:
ERROR_ACCESS_DENIED (5)
You have to call CreateFile first to see if the file is in use.
To see if the file is in use:
If you get a valid file handle then you know the file does not have conflicting sharing permissions with a process that already has this file open.
If you specify no sharing access (0 to the dwShareMode parameter of the CreateFile call), then you will not get a file handle if any other process is currently using that file in any way. GetLastError in this case would return:
ERROR_SHARING_VIOLATION (32)
To see if there is a security problem with accessing the file:
To see if there is a permissions problem accessing that file, the CreateFile call will also fail but with a different GetLastError. You will get:
ERROR_ACCESS_DENIED (5)