1

我有一个大型日志文件,需要在 Windows 8 上使用 F# 进行解析。服务器不断运行,通过添加新行来写入日志文件的末尾。每分钟检查一次日志文件是否有更改。我宁愿从最后读取并将新添加的行组合到先前解析的结果中,而不是重新解析整个文件。更好的是,我希望能够在文件更改时注册回调。那可能吗?

4

1 回答 1

1

您可以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"

但是,由于某种原因,在我的机器上出现“该进程无法访问该文件,因为它正在被另一个 proc 使用”错误,我无法追踪。这些use语句应该在超出范围时进行处理,甚至显式调用Close也不能解决它:/

于 2013-10-27T15:44:13.097 回答