C#中连续读取文件 [英] c# continuously read file
问题描述
我想读的文件不断像GNU尾巴-f参数。我需要它来住读取日志文件。
什么是做正确的方式?
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?
推荐答案
您想以二进制方式打开的FileStream
。定期,力求文件减去1024字节(或其他)的结尾,然后阅读到最后输出。这是-f 如何尾工作。
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 how tail -f
works.
问题的答案:
二进制,因为它是困难的,如果你读它作为文本随机访问文件。你必须自己做二进制到文本的转换,但它并不困难。 (见下文)
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个字节,因为它是一个很好的便利数,应该处理10或15行文字。通常
1024 bytes because it's a nice convenient number, and should handle 10 or 15 lines of text. Usually.
下面是打开文件,读的是最后1024个字节,并将其转换为文本的例子:
Here's an example of opening the file, reading the last 1024 bytes, and converting it to text:
static void ReadTail(string filename)
{
using (FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
// Seek 1024 bytes from the end of the file
fs.Seek(-1024, SeekOrigin.End);
// read 1024 bytes
byte[] bytes = new byte[1024];
fs.Read(bytes, 0, 1024);
// Convert bytes to string
string s = Encoding.Default.GetString(bytes);
// or string s = Encoding.UTF8.GetString(bytes);
// and output to console
Console.WriteLine(s);
}
}
请注意,你必须用 FileShare.ReadWrite
打开,因为你试图读取一个文件,该文件是当前打开的另一个进程的写作。
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.
另外请注意,我用 Encoding.Default
,这在美国/英语和大多数西欧语言将是一个8位字符编码。如果该文件是写在一些其他的编码(如UTF-8或其他统一code编码),这可能是字节将无法正确转换为字符。你必须通过确定的编码来处理,如果你认为这将是一个问题。搜索堆栈溢出的信息有关确定文件的文本编码。
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.
如果您想定期做到这一点(每15秒,例如),您可以设置经常只要你想调用 ReadTail
方法的计时器。可以通过在节目的开始打开文件仅一次优化事情有点。这是给你的。
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.
这篇关于C#中连续读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!