检查文件是否在使用中 [英] Check if file is in use

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

问题描述

我需要一些帮助.我正在尝试同时从多个客户端打开servern上的文本文件,因此在读取文件时不会锁定文件.像这样:

Hi guys I need some help. I'm trying to open a textfile on a servern from multiple clients at the same time so I'm not locking the file when reading from it. Like this:

new StreamReader(File.Open(logFilePath, 
                       FileMode.Open, 
                       FileAccess.Read, 
                       FileShare.ReadWrite))

现在,我正在尝试检查任何客户机是否都使用了此文件(因为我想为其添加新内容),但是由于我在读取文件时未锁定它,所以我不知道如何去做这个.我无法尝试打开并捕获异常,因为它将打开.

Now I'm trying to check if this file is used by any of the clients (because I want to write something new to it), but since I'm not locking it when reading from it I don't know how to do this. I can't try to open and catch an exception because it will open.

推荐答案

我无法尝试打开并捕获异常,因为它将打开

I can't try to open and catch an exception because it will open

为什么?以这种方式工作是一个有价值的选择.

Why ? It's a valuable option to work in that way.

通过这种方式,您还可以创建一个空的预定义文件(例如"access.lock"等),以便了解 actual 文件是否已锁定,请检查锁定文件是否存在:

By the way you can also create a some empty predefined file, say "access.lock", and others, in order to understand if the actual file is locked check on lock file presence:

if(File.Exist("access.lock")) 
  //locked 
else
  //write something

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

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