2

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

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

现在我正在尝试检查该文件是否被任何客户端使用(因为我想为它写一些新的东西),但是由于我在读取它时没有锁定它,所以我不知道该怎么做. 我无法尝试打开并捕获异常,因为它会打开。

4

2 回答 2

3

你可以试试这个吗?

或者观看这里已经提出的这个问题 ->有没有办法检查文件是否正在使用?

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;
}
于 2013-04-16T07:55:52.057 回答
2

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

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

顺便说一句,您还可以创建一些空的预定义文件,例如“access.lock”等,以了解实际文件是否被锁定检查锁定文件的存在:

if(File.Exist("access.lock")) 
  //locked 
else
  //write something
于 2013-04-16T07:32:27.670 回答