I want to read file continuously like GNU tail with "-f" param. I need it to live-read log file. What is the right way to do it?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
To continuously monitor the tail of the file, you just need to remember the length of the file before.
I had to use ASCIIEncoding, because this code isn't smart enough to cater for variable character lengths of UTF8 on buffer boundaries.
Note: You can change the Thread.Sleep part to be different timings, and you can also link it with a filewatcher and blocking pattern - Monitor.Enter/Wait/Pulse. For me the timer is enough, and at most it only checks the file length every second, if the file hasn't changed.
This is my solution
so, in your code you can do
More natural approach of using
FileSystemWatcher
:Here the main reading cycle stops to wait for incoming data and
FileSystemWatcher
is used just to awake the main reading cycle.If you are just looking for a tool to do this then check out free version of Bare tail
You want to open a
FileStream
in binary mode. Periodically, seek to the end of the file minus 1024 bytes (or whatever), then read to the end and output. That's howtail -f
works.Answers to your questions:
Binary because it's difficult to randomly access the file if you're reading it as text. You have to do the binary-to-text conversion yourself, but it's not difficult. (See below)
1024 bytes because it's a nice convenient number, and should handle 10 or 15 lines of text. Usually.
Here's an example of opening the file, reading the last 1024 bytes, and converting it to text:
Note that you must open with
FileShare.ReadWrite
, since you're trying to read a file that's currently open for writing by another process.Also note that I used
Encoding.Default
, which in US/English and for most Western European languages will be an 8-bit character encoding. If the file is written in some other encoding (like UTF-8 or other Unicode encoding), It's possible that the bytes won't convert correctly to characters. You'll have to handle that by determining the encoding if you think this will be a problem. Search Stack overflow for info about determining a file's text encoding.If you want to do this periodically (every 15 seconds, for example), you can set up a timer that calls the
ReadTail
method as often as you want. You could optimize things a bit by opening the file only once at the start of the program. That's up to you.