简体   繁体   English

如何检查文件是否已经打开?

[英]How do I check if a file is already open?

private void btnViewErrorLogFile_Click(object sender, EventArgs e)
{
    errorLogFileProcess = Process.Start(AppVars.ErrorLogFilePath);
}

The above opens a text file in notepad. 上面在记事本中打开一个文本文件。 It contains error logs for my application. 它包含我的应用程序的错误日志。

I do not want to allow the user to open multiples of this file. 我不想允许用户打开该文件的倍数。 So I do not want to have him/her click the button again and open another window of the same file. 因此,我不想让他/她再次单击该按钮并打开同一文件的另一个窗口。

How do I check if this file is open? 如何检查此文件是否打开? Note: I DO NOT want to close a (or all) notepad.exe processes because the user might have a notepad process open for something else other than my application file (which uses notepad.exe when the file is open). 注意:我不想关闭(或全部)notepad.exe进程,因为用户可能会为我的应用程序文件(打开文件时使用notepad.exe)以外的其他东西打开记事本进程。

So again, how do I go about checking whether the process I opened is already opened? 因此,我又该如何检查打开的进程是否已经打开?

Just had another re-read of your question. 刚刚再次阅读了您的问题。

If you want to force the user to close the active instance of Notepad (that you launched) before allowing them to open it again, keep the errorLogFileProcess instance around and then recheck it before allowing the command. 如果要强制用户关闭(启动的)记事本的活动实例,然后再允许其打开,请保留errorLogFileProcess实例errorLogFileProcess ,然后在允许该命令之前对其进行重新检查。

Process errorLogFileProcess;

private void btnViewErrorLogFile_Click(object sender, EventArgs e)
{
    if (errorLogFileProcess != null)
    {
        // Process was launched previously; check if exited.
        if (!errorLogFileProcess.HasExited)
        {
            throw new Exception("Can't launch until first one closed.");
        }
    }

    errorLogFileProcess = Process.Start(AppVars.ErrorLogFilePath);
}

Could also use the errorLogFileProcess.HasExited state to disable the button so that the Click event is not raised. 也可以使用errorLogFileProcess.HasExited状态禁用按钮,以便不会引发Click事件。

在此处检查如何检查文件是否已打开(通过使用try,catch块): 检查文件是否已打开

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM