简体   繁体   English

Delphi:检查文件是否正在使用

[英]Delphi: Check whether file is in use

I want to write to/delete a file but sometimes I get a crash if the file is in use by another program. 我想写入/删除文件,但是如果另一个程序正在使用该文件,有时会崩溃。 How do I check to see whether the file is opened by another process or I can open it for writing? 如何检查文件是否已被另一个进程打开或可以打开以进行写入?

The problem is, that between the time you check to see if you could get exclusive access and opening the file, something else gets exclusive access to the file, and you get the exception anyway. 问题是,在您检查是否可以获取独占访问权和打开文件之间,还有其他东西获得了对该文件的独占访问权,无论如何您都获得了异常。

The only fool proof way to see if you can get an exclusive lock on a file is to try and get an exclusive lock on the file, if you get it you have it. 看看是否可以在文件上获得排他锁的唯一可靠方法是尝试在文件上获得排他锁(如果拥有)。

If not, you catch the exception, and either 如果不是,则捕获异常,或者

  • Go do something else 去做别的事情
  • Wait a while and try again 请稍等,然后重试

It's one of life's situations where it's better to ask for forgiveness than permission :) 这是生活中的一种情况,最好是请求宽恕比允许:)

There is a new way to get the origin of file locking for Vista and up here: http://www.remkoweijnen.nl/blog/2011/01/03/cannot-access-files-but-need-the-origin/ 有一种新的方法可以获取Vista和更高版本的文件锁定来源: http//www.remkoweijnen.nl/blog/2011/01/03/cannot-access-files-but-need-the-origin/

UserMode: The best way to write to a locked file is to ask the user to close it in the other process. UserMode:写入锁定文件的最佳方法是要求用户在其他过程中将其关闭。 In batch processes you should ignore such a file and log the problem. 在批处理过程中,您应忽略此类文件并记录问题。 Providing the name of the other process is a very good way to find a solution for the user. 提供其他进程的名称是为用户找到解决方案的一种很好的方法。

Not sure in which programming language you'd like to check if you can write to a file. 不确定要使用哪种编程语言检查是否可以写入文件。 In Java, java.io.File.canWrite() can do the job for you. 在Java中, java.io.File.canWrite()可以为您完成这项工作。

General: 一般:

In UNIX-like OS, you can use the lsof command. 在类似UNIX的操作系统中,可以使用lsof命令。

If you want to see which program holds a handle to your file, use the Process Monitor (download from MicroSoft). 如果要查看哪个程序保存了文件的句柄,请使用过程监视器 (从MicroSoft下载)。

This tool has a command line interface, so you could use your language's scripting interface (for example java.lang.Process ) to run the tool and display a useful error message. 该工具具有命令行界面,因此您可以使用语言的脚本界面(例如java.lang.Process )来运行该工具并显示有用的错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM