简而言之,我正在尝试使用Reactive Library实现一个简单的尾部实用程序,以便在将新行附加到文件时主动监视新行。这是我到目前为止所得到的:
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返回新行的列表。理想情况下,可观察序列只是表示每个新行的字符串。 observable返回List的唯一原因是因为我根本不知道如何按摩它来这样做。任何帮助将不胜感激。
答案 0 :(得分:1)
您可以使用SelectMany:
SelectMany(lines => lines)
.Subscribe(Observer.Create<string>(line => { Console.WriteLine("new line = {0}", line); });