我想创建一个控制台应用程序,它将读取一个文件,并监控每一个新行,因为它每 .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/