C# 检查文件是否正在使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16031145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:46:34  来源:igfitidea点击:

Check if file is in use

c#filelocking

提问by user2099024

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.

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

采纳答案by Tigran

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.

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

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

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

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

回答by Mehdi Bugnard

Do you can try this?

你可以试试这个吗?

Or watch this question already asked here ->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;
}