3

要するに、私は Reactive Library を使用して単純な tail ユーティリティを実装し、ファイルに追加された新しい行をアクティブに監視しようとしています。これが私がこれまでに得たものです:

    static void Main(string[] args)
    {
        var filePath = @"C:\Users\wbrian\Documents\";
        var fileName = "TestFile.txt";
        var fullFilePath = filePath + fileName;
        var fs = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        var sr = new StreamReader(fs, true);
        sr.ReadToEnd();
        var lastPos = fs.Position;

        var watcher = new FileSystemWatcher(filePath, fileName);
        watcher.NotifyFilter = NotifyFilters.Size;
        watcher.EnableRaisingEvents = true;

        Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
            action => watcher.Changed += action,
            action => watcher.Changed -= action)
             .Throttle(TimeSpan.FromSeconds(1))
             .Select(e =>
                 {
                     var curSize = new FileInfo(fullFilePath).Length;
                     if (curSize < lastPos)
                     {
                         //we assume the file has been cleared,
                         //reset the position of the stream to the beginning.
                         fs.Seek(0, SeekOrigin.Begin);
                     }
                    var lines = new List<string>();
                    string line;
                    while((line = sr.ReadLine()) != null)
                    {
                        if(!string.IsNullOrWhiteSpace(line))
                        {
                            lines.Add(line);
                        }
                    }
                     lastPos = fs.Position;
                     return lines;
                 }).Subscribe(Observer.Create<List<string>>(lines =>
                 {
                     foreach (var line in lines)
                     {
                         Console.WriteLine("new line = {0}", line);
                     }
                 }));

        Console.ReadLine();
        sr.Close();
        fs.Close();
    }

ご覧のとおり、ファイルのサイズが変更されたときに発生するイベントである FileWatcher イベントから Observable を作成します。そこから、どの行が新しいかを判断し、オブザーバブルは新しい行のリストを返します。理想的には、オブザーバブル シーケンスは、新しい各行を表す単なる文字列になります。オブザーバブルがリストを返す唯一の理由は、そのようにするためにそれをマッサージする方法がわからないからです。どんな助けでも大歓迎です。

4

1 に答える 1

1

SelectManyを使用できます:

SelectMany(lines => lines)
.Subscribe(Observer.Create<string>(line => { Console.WriteLine("new line = {0}", line); });
于 2013-01-10T23:00:31.233 に答える