我试图在日志文件的文本框中添加新行,日志文件会经常更新。我有一个FileSystemWatcher
检查文件中是否有任何更新并触发onChange()
event的事件。
textbox1.Text = File.ReadAllText(@"D:\Serverlogs\clientList.log");
随着日志大小的增加,此操作将获取整个文件的内容,此操作变得越来越慢。如何读取更新的行而不是整个文件?
服务器会将新登录用户的列表更新到日志中,例如,文件中和文本框中有15行文本,服务器中的每个新日志更新文件后,我只需要阅读第16行线。
我认为您必须跟踪文件中读取的最后一个位置,然后在检测到更改时:打开文件,查找到正确的位置,然后读取到最后。然后将其解析为几行,以添加到文本框中。
编辑:这是一个工作的控制台应用程序,演示了此。您将需要更多的错误检查,初始化等等。旧代码只是一个猜测,但基本上是正确的。
class Program
{
static FileSystemWatcher fs = null;
static string fileName = @"c:\temp\log.txt";
static long oldPosition = 0;
static void Main(string[] args)
{
fs = new FileSystemWatcher(Path.GetDirectoryName(fileName));
fs.Changed += new FileSystemEventHandler(fs_Changed);
fs.EnableRaisingEvents = true;
Console.WriteLine("Waiting for changes to " + fileName);
Console.ReadLine();
}
static void fs_Changed(object sender, FileSystemEventArgs e)
{
if (e.FullPath != fileName || e.ChangeType != WatcherChangeTypes.Changed) return;
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (StreamReader fr = new StreamReader(fs))
{
Console.WriteLine("{0} changed. Old Postion = {1}, New Length = {2}", e.Name, oldPosition, fs.Length);
if (fs.Length > oldPosition)
{
fs.Position = oldPosition;
var newData = fr.ReadToEnd();
Console.WriteLine("~~~~~~ new data ~~~~~~\n" + newData);
oldPosition = fs.Position;
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句