1

我遇到了一个问题FileSystemWatcher。我收听某个文本文件,并且每个新行(FileSystemWatcher.Changed)都是句柄。 Text file我听的是在本地网络上,一些计算机可以同时写入文件。当一台特定的机器写我的文本文件时,我立即取出文件中的最后一行并处理它。如何验证例如某些机器是否在我从每台机器中获取此字符串的同时写入文件而没有错过?

这是我的课:

public class Watcher
{
    private string _file;

    public Watcher(string file)
    {
        _file = file;
    }

    public void startWatch()
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = Path.GetDirectoryName(_file);
        watcher.Filter = Path.GetFileName(_file);
        watcher.NotifyFilter = NotifyFilters.LastWrite;
        watcher.Changed += watcher_Changed;
        watcher.EnableRaisingEvents = true;
    }

    public void watcher_Changed(object sender, FileSystemEventArgs e)
    {
        readLastLine();
    }

    private void readLastLine()
    {
        string lastLine = string.Empty;
        using (StreamReader sr = new StreamReader(File.Open(_file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
        {
            string str = sr.ReadToEnd();
            int x = str.LastIndexOf('\n');
            lastLine = str.Substring(x + 1);
        }

        validateString(lastLine);
    }

    private void validateString(string str)
    {
        string[] arr = str.Split(' ');

        if (arr.Length != 2 && arr[0] != "start" && arr[0] != "stop" && arr[0] != "finish")
            return;

        // Handle the string...
    }
}
4

0 回答 0