如何读取在 C# 中每小时更新的日志文件?
How to read a log file which is hourly updated in c#?
我正在尝试用 C# 编写一个读取日志文件的控制台应用程序。我面临的问题是这个日志文件每 1 小时更新一次,例如,如果我在开始时有 10 行,之后有 12 行,在我的第二次读取尝试中,我将不得不只读取 2 条新添加的行。
您能否建议我一种有效执行此操作的方法(无需再次读取所有行,因为日志文件通常有 5000 多行)?
首先,您可以使用FileSystemWatcher
在文件更改后收到通知。
此外,您可以使用 FileStream
和 Seek
函数只准备新添加的行。在 http://www.codeproject.com/Articles/7568/Tail-NET 上有一个 Thread.Sleep
的例子:
using ( StreamReader reader = new StreamReader(new FileStream(fileName,
FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) )
{
//start at the end of the file
long lastMaxOffset = reader.BaseStream.Length;
while ( true )
{
System.Threading.Thread.Sleep(100);
//if the file size has not changed, idle
if ( reader.BaseStream.Length == lastMaxOffset )
continue;
//seek to the last max offset
reader.BaseStream.Seek(lastMaxOffset, SeekOrigin.Begin);
//read out of the file until the EOF
string line = "";
while ( (line = reader.ReadLine()) != null )
Console.WriteLine(line);
//update the last max offset
lastMaxOffset = reader.BaseStream.Position;
}
}
我正在尝试用 C# 编写一个读取日志文件的控制台应用程序。我面临的问题是这个日志文件每 1 小时更新一次,例如,如果我在开始时有 10 行,之后有 12 行,在我的第二次读取尝试中,我将不得不只读取 2 条新添加的行。 您能否建议我一种有效执行此操作的方法(无需再次读取所有行,因为日志文件通常有 5000 多行)?
首先,您可以使用FileSystemWatcher
在文件更改后收到通知。
此外,您可以使用 FileStream
和 Seek
函数只准备新添加的行。在 http://www.codeproject.com/Articles/7568/Tail-NET 上有一个 Thread.Sleep
的例子:
using ( StreamReader reader = new StreamReader(new FileStream(fileName,
FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) )
{
//start at the end of the file
long lastMaxOffset = reader.BaseStream.Length;
while ( true )
{
System.Threading.Thread.Sleep(100);
//if the file size has not changed, idle
if ( reader.BaseStream.Length == lastMaxOffset )
continue;
//seek to the last max offset
reader.BaseStream.Seek(lastMaxOffset, SeekOrigin.Begin);
//read out of the file until the EOF
string line = "";
while ( (line = reader.ReadLine()) != null )
Console.WriteLine(line);
//update the last max offset
lastMaxOffset = reader.BaseStream.Position;
}
}