c# - 读取文件,并监视新行

标签 c# .net console-application filestream

我想创建一个控制台应用程序,它将读取一个文件,并监控每一个新行,因为它每 .5 秒就会被另一个进程写入一次。

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

最佳答案

听起来您想要一个适用于 Windows 的 tail 版本。请参阅“Looking for a windows equivalent of the unix tail command”以了解相关讨论。

否则,open the file在不阻止其他进程使用 FileShare.ReadWrite 访问的情况下.寻找到最后阅读然后使用Thread.Sleep()Task.Delay()在查看是否有任何变化之间等待半秒钟。

例如:

public static void Follow(string path)
{
    // Note the FileShare.ReadWrite, allowing others to modify the file
    using (FileStream fileStream = File.Open(path, FileMode.Open, 
        FileAccess.Read, FileShare.ReadWrite))
    {
        fileStream.Seek(0, SeekOrigin.End);
        using (StreamReader streamReader = new StreamReader(fileStream))
        {
            for (;;)
            {
                // Substitute a different timespan if required.
                Thread.Sleep(TimeSpan.FromSeconds(0.5));

                // Write the output to the screen or do something different.
                // If you want newlines, search the return value of "ReadToEnd"
                // for Environment.NewLine.
                Console.Out.Write(streamReader.ReadToEnd());
            }
        }
    }
}

关于c# - 读取文件,并监视新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23306089/

相关文章:

c# - ASP.NET MVC C# Razor 缩小

c# - 多重编辑上的 MVC 模型绑定(bind)

c# - 仅更改 RichTextBox 字体系列而不更改 FontSize

.net - 如何通过对象值从 List(Of myClass) 中删除对象?

python - 你如何制作一个接受命令的控制台应用程序?

c# - Powershell 输出格式

c# - 如何在其他类中赋值?

.net - 使用Linq to SQL设置SQL查询时间的好方法

delphi - 在控制台应用程序中屏蔽密码输入

c++ - 在控制台窗口关闭时优雅地关闭命令行应用程序(在 Windows 上)