简体   繁体   English

FileSystemWatcher检测到更改后,读取文本文件的最后一行

[英]Read last line of text file after FileSystemWatcher detects change

I am new to c# so please forgive my ignorance, I am running a fileSystemWatcher on a text file. 我是C#的新手,所以请原谅我的无知,我正在文本文件上运行fileSystemWatcher。 And it is working fine, I can do some simple tasks after the file has changed. 而且工作正常,文件更改后,我可以执行一些简单的任务。 All but what I want to do. 除了我想做什么。 I am trying to read the last line of the text file that has changed with this code 我正在尝试读取此代码已更改的文本文件的最后一行

public void File_Changed( object source, FileSystemEventArgs e )
{
    string MACH1 = File.ReadText(@"C:\MACHINE_1.txt").Last();
    if (MACH1=="SETUP")
    {
        MACHINE1IND.BackColor = Color.Green; 
    }
    else
    {
        MACHINE1IND.BackColor = Color.Red; 
    }
}

It works fine inside a button but not after file watcher. 它在按钮内运行良好,但在文件监视程序之后则无法运行。 Says it cannot find file? 说找不到文件?

One thing to be aware of is that the FSW can issue multiple change notifications during a save operation. 要注意的一件事是,FSW可以在保存操作期间发出多个更改通知。 You have no way of knowing when the save is complete. 您无法知道保存何时完成。 As a result, you need to always wrap your code in a try..catch block and support retry after a timeout to allow the file write to be completed. 因此,您需要始终将代码包装在try..catch块中,并在超时后支持重试以允许完成文件写入。 Typically, I will try to move the file to a temp location where I will do my processing. 通常,我将尝试将文件移动到临时位置进行处理。 If the move fails, wait a couple seconds and try again. 如果移动失败,请等待几秒钟,然后重试。

You'll have to check if the file exists before accessing it. 在访问文件之前,您必须检查文件是否存在。

public void File_Changed(object source, FileSystemEventArgs e)
{
    string filePath = @"C:\MACHINE_1.txt";
    if(!File.Exists(filePath)) //Checks if file exists
        return;
    string MACH1 = File.ReadText(filePath).Last();
    if (MACH1=="SETUP")
    {
        MACHINE1IND.BackColor = Color.Green; 
    }
    else
    {
        MACHINE1IND.BackColor = Color.Red; 
    }
}

As Jim Wooley explains in his answer, the file operation might still be in progress, when FSW fires a Created or Changed event. 正如Jim Wooley在回答中解释的那样,当FSW触发CreatedChanged事件时,文件操作可能仍在进行中。 If FSW is used to communicate between two applications and you are in control of the "sending" application as well, you can solve the problem as follows: 如果使用FSW在两个应用程序之间进行通信,并且您也可以控制“发送”应用程序,则可以解决以下问题:

Write the information to a temporary file. 将信息写入临时文件。 Close the file. 关闭文件。 Rename the temporary file and give it a definitive name. 重命名临时文件,并为其指定一个明确的名称。

In the other application (the receiver) watch for the Renamed event using the FileSystemWatcher . 在另一个应用程序(接收者)中,使用FileSystemWatcher监视Renamed事件。 The renamed file is guaranteed be complete. 重命名的文件可以保证是完整的。

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

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