读取文件,并监视换行 [英] Reading file, and monitor new line

查看:66
本文介绍了读取文件,并监视换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望创建一个控制台应用程序,该应用程序将读取文件,并监视每行新记录,因为每隔0.5秒它就会被另一个进程写入。

I'm looking to create a console application that will read a file, and monitor every new line since it's being write by another process every .5 seconds.

如何在使用.NET 4.5的控制台应用程序中实现这一目标?

How can I achieve that, within a Console App using .NET 4.5?

推荐答案

如@Sudhakar所述,当您使用FileSystemWatcher时,它很有用希望在文件偶尔更新时收到通知,而当您要不断处理不断增长的文件(例如繁忙的日志文件)中的信息时,定期轮询很有用。

As @Sudhakar mentioned, FileSystemWatcher is useful when you want to be notified when a file updates sporadically, and polling at regular intervals is useful when you want to be constantly processing information from an always-growing file (such as a busy log file).

我想添加一个关于效率的注释。如果您担心处理大文件(许多MB或GB)的效率和速度,那么您将希望在阅读和处理更新时跟踪文件中的位置。例如:

I'd like to add a note about efficiency. If you are concerned with the efficiency and speed of processing large files (many MB or GB), then you will want to track your position in the file as you read and process updates. For example:

// This does exactly what it looks like.
long position = GetMyLastReadPosition();

using (var file = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    if (position == file.Length)
        return;

    file.Position = position;
    using (var reader = new StreamReader(file))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            // Do reading.
        }
        position = file.Position; // Store this somewhere too.
    }
}

这应该使您避免重新处理a的任何部分您已经处理过的文件。

This should allow you to avoid reprocessing any part of a file that you have already processed.

这篇关于读取文件,并监视换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆