什么是检测文件是否在Windows中打开的编程方式? [英] What's a programmatic way to detect if a file is opened in Windows?

查看:123
本文介绍了什么是检测文件是否在Windows中打开的编程方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种简单的方法来检测是否在Windows中的任何进程中打开文件?



例如,我正在监视一个目录,如果文件被放入我想对这些文件执行一些操作。



我不想执行这些操作,如果文件仍然被复制到目录中,或者如果这些文件的内容仍然被更新。

所以,发生了什么是给定一个文件名,我想要实现一个函数,如函数 IsFileOpenedAnywhereElseInAnyProcess(const PathName:string):Boolean ,返回 true false

我可以想到的一种方法是重命名文件,如果重命名成功,没有其他进程打开我感兴趣的文件,像这样:

 函数IsFileOpenedAnywhereElseInAnyProcess(const PathName:string):Boolean; 
begin
Result:= not(MoveFileEx(PathName,PathName +'。BLAH',0)and MoveFileEx(PathName +'。BLAH',PathName,0));
end;

逻辑是如果我可以重命名文件(到另一个扩展名),然后重命名它,这不是

谢谢。

解决方案

















$ b $ <这是一个你永远无法在多任务操作系统上正确实现的功能。你会得到一个错误的回报,一个纳秒后,另一个进程打开文件,并毁了你的一天。

正确做到这一点的唯一方法是做到这一点原子,实际上试图打开文件。并指定不共享,以便其他进程也可以打开该文件。如果另一个进程已经获得对该文件的访问权限,那么将会失败并返回ERROR_SHARING_VIOLATION。此时您需要稍等一会,稍后再试。


Is there a simple way to detect if a file is opened in any process in Windows?

For example, I am monitoring a directory and if files are placed into the directory, I want to perform some actions on these files.

I do not want to perform these actions, if the files are still being copied into the directory, or if the contents of these files are still being updated.

So, what's happening is that given a filename, I want to implement a function, such as function IsFileOpenedAnywhereElseInAnyProcess(const PathName: string): Boolean, that returns either true or false.

One of the ways I can think of, is to rename the file, and if the rename succeeds, no other processes have opened the file I'm interested in, like so:

function IsFileOpenedAnywhereElseInAnyProcess(const PathName: string): Boolean;
begin
  Result := not (MoveFileEx(PathName, PathName+'.BLAH', 0) and MoveFileEx(PathName+'.BLAH', PathName, 0));
end;

The logic being if I can rename the file (to another extension) then rename it back, it's not opened by any other process (at the time of checking).

Thanks.

解决方案

IsFileOpenedAnywhereElseInAnyProcess(const PathName: string): Boolean

That's a function that you can never implement correctly on a multi-tasking operating system. You'll get a False return and a nanosecond later another process opens the file and ruins your day.

The only way to do this correctly is to do this atomically, actually attempting to open the file. And specify no sharing so that no other process may open the file as well. That will fail with ERROR_SHARING_VIOLATION if another process already gained access to the file. At which point you'll have a wait a while and try again later.

这篇关于什么是检测文件是否在Windows中打开的编程方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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