mirror of
https://gitee.com/xiarenalofs/squad-rain-ops-mini.git
synced 2026-08-13 16:05:42 +08:00
62 lines
1.7 KiB
C#
62 lines
1.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System;
|
|
using System.IO;
|
|
using System.Timers;
|
|
|
|
namespace RainOpsMini.Helpers
|
|
{
|
|
|
|
public class RealtimeFileReader
|
|
{
|
|
private readonly string _filePath;
|
|
private long _lastPosition = 0;
|
|
private readonly System.Timers.Timer _timer;
|
|
|
|
public event Action<string> OnNewLine;
|
|
|
|
public RealtimeFileReader(string filePath, double intervalMs = 100)
|
|
{
|
|
_filePath = filePath;
|
|
|
|
_timer = new System.Timers.Timer(intervalMs);
|
|
_timer.Elapsed += Timer_Elapsed;
|
|
_timer.AutoReset = true;
|
|
}
|
|
|
|
public void Start() => _timer.Start();
|
|
public void Stop() => _timer.Stop();
|
|
|
|
private void Timer_Elapsed(object? sender, ElapsedEventArgs e)
|
|
{
|
|
try
|
|
{
|
|
using (var fs = new FileStream(_filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
|
|
{
|
|
if (_lastPosition > fs.Length)
|
|
_lastPosition = 0; // 文件被截断或重写了
|
|
|
|
fs.Seek(_lastPosition, SeekOrigin.Begin);
|
|
using (var reader = new StreamReader(fs))
|
|
{
|
|
string? line;
|
|
while ((line = reader.ReadLine()) != null)
|
|
{
|
|
OnNewLine?.Invoke(line); // 触发回调
|
|
}
|
|
|
|
_lastPosition = fs.Position;
|
|
}
|
|
}
|
|
}
|
|
catch (IOException)
|
|
{
|
|
// 可选:忽略文件正被写入的异常
|
|
}
|
|
}
|
|
}
|
|
}
|