gpt4 book ai didi

c# - 如何在 C# 中由服务器更新的文件中的文本框中追加更新的行?

转载 作者:行者123 更新时间:2023-11-30 20:54:36 24 4
gpt4 key购买 nike

我正在尝试从日志文件中在文本框中追加新行,日志文件经常更新。我有一个 FileSystemWatcher,它检查文件中的任何更新并触发 onChange() 事件。

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;
}
}
}
}

关于c# - 如何在 C# 中由服务器更新的文件中的文本框中追加更新的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18998009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com