使用MemoryMappedFile和FileSystemWatcher检测到日志文件的新条目 [英] Using MemoryMappedFile and FileSystemWatcher to detect new entries to logfile

查看:45
本文介绍了使用MemoryMappedFile和FileSystemWatcher检测到日志文件的新条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由第三方应用程序编写的日志文件,我希望我的应用程序实时/近距离地读取"该日志文件,解析新的日志条目并对某些事件采取行动.

I have a logfile that is written by a 3rd party application and I'd like my application to "read" that log file in real/near-time, parse the new log entries and act upon certain events.

我的想法是,我可以结合使用FileSystemWatcher(以信号通知文件更改)和MemoryMappedFile(以从特定偏移量继续读取)来实现这一目标.

My thought was that I could achieve this with a combination of FileSystemWatcher (to signal file changes) and MemoryMappedFile (to continue reading from a certain offset).

但是,由于这是我第一次使用MemoryMappedFiles,所以确实遇到了一些问题,这可能是由于不正确地理解该概念而引起的(例如,由于其他进程正在使用该文件,因此我无法打开它)).

However, since this is the first time I'm using MemoryMappedFiles I do run into some issues which probably arise from not understanding the concept correctly (e.g. I'm unable to open the existing File as it's in use by the other process).

我想知道是否有人举了一个例子,说明如何使用MemoryMappedFiles读取被另一个进程锁定的文件?

I was wondering if someone has an example of how to use MemoryMappedFiles to read a file that is locked by another process?

谢谢

汤姆

从注释中看,内存映射文件"似乎无法帮助我访问具有排他锁的文件.但是,尾部"工具例如Baretail(http://www.baremetalsoft.com/baretail/index.php)能够做到这一点.以1秒的间隔从另一个应用程序读取具有互斥锁的文件没有问题.因此,必须有某种方法可以做到这一点?

From the comments, it looks like Memory Mapped Files won't help me accessing files that have an exclusive lock. However, "tail" tools like, e.g. Baretail (http://www.baremetalsoft.com/baretail/index.php) are able to do just that. It has no problem reading the file that has an exclusive lock from another application in 1s intervals). So, there has to be some way to do this?

EDITEDIT :

要回答我自己的问题,打开锁定文件的诀窍是使用以下访问标志创建FileStream:

To answer my own question, the trick in opening a locked file is, creating the FileStream with the following access flags:

fileStream = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite);

推荐答案

要回答我自己的问题,读取锁定文件的技巧是使用以下访问标志创建FileStream:

To answer my own question, the trick in reading a locked file is creating the FileStream with the following access flags:

FileStream fileStream = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite);

现在只需进行基于时间间隔的轮询或查找FileSystemWatcher更改事件以检测文件更改

Now it's just a matter of either doing interval based polling or looking for FileSystemWatcher change events to detect file changes

这篇关于使用MemoryMappedFile和FileSystemWatcher检测到日志文件的新条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆