c#连续读取文件

标签 c# file-io

我想像 GNU tail 一样用“-f”参数连续读取文件。我需要它来实时读取日志文件。 正确的做法是什么?

最佳答案

使用 FileSystemWatcher 的更自然的方法:

    var wh = new AutoResetEvent(false);
    var fsw = new FileSystemWatcher(".");
    fsw.Filter = "file-to-read";
    fsw.EnableRaisingEvents = true;
    fsw.Changed += (s,e) => wh.Set();

    var fs = new FileStream("file-to-read", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    using (var sr = new StreamReader(fs))
    {
        var s = "";
        while (true)
        {
            s = sr.ReadLine();
            if (s != null)
                Console.WriteLine(s);
            else
                wh.WaitOne(1000);
        }
    }

    wh.Close();

这里主读取周期停止等待传入数据,FileSystemWatcher 用于唤醒主读取周期。

关于c#连续读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49700285/

相关文章:

android - 自定义 ContentProvider - openInputStream()、openOutputStream()

c# - 将约束类型传递给方法

c - 有没有办法让 scanf 从文件中读取

c++ - 为什么数组中的数据被删除后还能用?

c# - 来自 C# 代码的 SQL Lead 和 Lag 函数

c - 如果我不在 C 程序中调用 fclose() 会发生什么?

C - fwrite - 无法打开文件,因为它包含无效字符

c# - Linq 多对多包括

c# - 从c#中的列表中显示类的数据

c# - XML 错误 : There are multiple root elements