我有一个很大的日志文件,需要在Windows8上使用F#进行解析。服务器一直在运行,它会通过添加新行来写入日志文件的末尾。每分钟检查一次日志文件的更改。与其重新解析整个文件,我宁愿只从末尾读取,并将新添加的行与上一次解析的结果组合在一起。更好的是,每当文件发生变化时,我都希望能够注册一个回调。这有可能吗?
发布于 2013-10-27 23:44:13
你可以通过文件流Seek()来做到这一点。如下所示:
open System.IO
let WatchLog directory file =
// Keep track of last read position
let lastRead = ref 0L
// Function that's called whenever the file changes
let processLog (e : FileSystemEventArgs) =
// Open file, and seek to the last read location
use fs = new FileStream(Path.Combine(directory, file), FileMode.Open, FileAccess.Read)
fs.Seek(!lastRead, SeekOrigin.Begin) |> ignore
// Read the rest of the file
use sr = new StreamReader(fs)
printfn "Reading log: %A" (sr.ReadToEnd())
// Store the length so that we know how much to seek over next time
lastRead := fs.Length
()
// Create a FS watched to be notified when a file changes
let fs = new FileSystemWatcher(directory, file)
fs.Changed.Add(processLog)
fs.EnableRaisingEvents <- true
WatchLog "M:\Coding\" "TestLog.txt"然而,由于某些原因,在我的机器上,我得到了“进程无法访问文件,因为它正被另一个进程使用”的错误,我无法跟踪它。当use语句超出作用域时,它们应该被处理,甚至对Close的显式调用也不能解决这个问题:/
https://stackoverflow.com/questions/11180971
复制相似问题