读取文件,并监视换行

Dek*_*kim 3 .net c# console-application filestream

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

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

akt*_*ton 5

听起来您想要Windows的tail版本。有关此内容的讨论,请参见“ 寻找与unix tail命令等效的Windows ”。

否则,请不阻止使用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());
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)