2013-04-16 84 views
2

嗨,大家好,我需要一些帮助。我试图在同一时间从多个客户端的servern上打开一个文本文件,所以我在读取文件时没有锁定文件。就像这样:检查文件是否正在使用

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

现在我想要检查,如果该文件是由任何客户机使用(因为我想写一些新的东西的话),但读的时候,因为我没有将其锁定它我不知道该怎么做。我无法尝试打开并捕获异常,因为它会打开。

+1

阅读本 http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-正在使用的文件 – Roar

+0

这显示了如何通过检查文件是否被锁定来检查文件是否正在使用。不是我的问题 – user2099024

+0

请参阅http://stackoverflow.com/questions/15362518/checking-if-a-file-is-in-use-without-try-catch – LMeyer

回答

2

我不能尝试打开并捕获一个例外,因为它会打开

为什么?以这种方式工作是一个宝贵的选择。

到时候你还可以创建一个空的一些预定义的文件的方式,说“access.lock”,和其他人,以了解是否实际文件被锁定支票锁定文件存在:

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

你可以试试吗?

,或者已经看这个问题,在这里问 - >Is there a way to check if a file is in use?

protected virtual bool IsFileLocked(FileInfo file) 
{ 
    FileStream stream = null; 

    try 
    { 
     stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); 
    } 
    catch (IOException) 
    { 
     //the file is unavailable because it is: 
     //still being written to 
     //or being processed by another thread 
     //or does not exist (has already been processed) 
     return true; 
    } 
    finally 
    { 
     if (stream != null) 
      stream.Close(); 
    } 

    //file is not locked 
    return false; 
}