Delphi:检查文件是否正在使用 [英] Delphi: Check whether file is in use

查看:205
本文介绍了Delphi:检查文件是否正在使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写入/删除文件,但是如果文件正被另一个程序使用,有时会崩溃.如何检查文件是否由其他进程打开或可以打开以进行写入?

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

  • 去做别的事
  • 请稍等,然后重试

这是生活中的一种情况,要求宽恕比获得许可要好:)

It's one of life’s situations where it's better to ask for forgiveness than permission :)

这篇关于Delphi:检查文件是否正在使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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