代码之家  ›  专栏  ›  技术社区  ›  user584018

如何获取文件的增量内容

  •  1
  • user584018  · 技术社区  · 7 年前

    我正在使用名为 ReactiveFileSystemWatcher 哪里 ObservableFileSystemWatcher 是围绕 FileSystemWatcher .

    我的文本文件不断添加新内容,我只想获取增量更改。

    下面的代码会在文件内容发生更改时发出通知,但我想在文件中附加什么内容?

    using RxFileSystemWatcher;
    using System;
    using System.Linq;
    using System.Reactive.Linq;
    
    namespace ConsoleApp1
    {
    class Program
    {
        static void Main(string[] args)
        {
    
            using (var watcher = new ObservableFileSystemWatcher(c => { c.Path = @"C:\Test\"; c.IncludeSubdirectories = true; }))
            {
                watcher.Changed.Select(x => $"{x.Name} was {x.ChangeType}").Subscribe(Console.WriteLine);
                watcher.Start();
                Console.ReadLine();
            }
        }
    
    }
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Anders Marzi Tornblad    7 年前

    如果您知道文件总是只附加到,并且中间的某个地方没有发生任何更改,那么可以通过跟踪您正在查看的所有文件的长度来解决此问题。当有任何更改时,您只需将文件内容从旧长度读取到文件的新端即可。

    Dictionary<string, long> lengthByFilename = new Dictionary<string, long>();
    // TODO: recurse through all existing files to get their lengths and put in 
    //       the dictionary
    
    watcher.Changed.Select(x => {
        string addedContent;
        using (var file = File.OpenRead(x.Name)) {
            // Seek to the last known end position
            if (lengthByFilename.ContainsKey(x.Name)) {
                file.Seek(lengthByFilename[x.Name], SeekOrigin.Begin);
            }
    
            using (var reader = new StreamReader(file)) {
                addedContent = reader.ReadToEnd();
            }
        }
    
        // Update dictionary with new length
        lengthByFilename[x.Name] = (new FileInfo(x.Name)).Length;
    
        return $"{x.Name} has had this added: {addedContent}";
    }).Subscribe(Console.WriteLine);
    

    显然,这段代码严重缺乏错误处理,但这只是一个开始。您必须捕获IOExceptions,并考虑如何以适当的方式处理锁定的文件。您可能需要实现一个事件队列,可以对其进行迭代以尝试并重新尝试读取新内容。