简而言之,我正在尝试使用 Reactive Library 来实现一个简单的 tail 实用程序,以便在将新行附加到文件时主动监控它们。这是我到目前为止得到的:
static void Main(string[] args)
{
var filePath = @"C:\Users\wbrian\Documents\";
var fileName = "TestFile.txt";
var fullFilePath = filePath + fileName;
var fs = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var sr = new StreamReader(fs, true);
sr.ReadToEnd();
var lastPos = fs.Position;
var watcher = new FileSystemWatcher(filePath, fileName);
watcher.NotifyFilter = NotifyFilters.Size;
watcher.EnableRaisingEvents = true;
Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
action => watcher.Changed += action,
action => watcher.Changed -= action)
.Throttle(TimeSpan.FromSeconds(1))
.Select(e =>
{
var curSize = new FileInfo(fullFilePath).Length;
if (curSize < lastPos)
{
//we assume the file has been cleared,
//reset the position of the stream to the beginning.
fs.Seek(0, SeekOrigin.Begin);
}
var lines = new List<string>();
string line;
while((line = sr.ReadLine()) != null)
{
if(!string.IsNullOrWhiteSpace(line))
{
lines.Add(line);
}
}
lastPos = fs.Position;
return lines;
}).Subscribe(Observer.Create<List<string>>(lines =>
{
foreach (var line in lines)
{
Console.WriteLine("new line = {0}", line);
}
}));
Console.ReadLine();
sr.Close();
fs.Close();
}
如您所见,我从 FileWatcher 事件创建了一个 Observable,该事件在文件大小更改时触发。从那里,我确定哪些行是新的,并且 observable 返回一个新行列表。理想情况下,可观察序列将只是一个代表每个新行的字符串。可观察返回列表的唯一原因是因为我根本不知道如何按摩它来做到这一点。任何帮助将不胜感激。