简体   繁体   中英

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).

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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