c#连续读取文件 [英] c# continuously read file
问题描述
我想像 GNU tail 一样使用-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 字节(或其他),然后读取到末尾并输出.这就是 tail -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 或其他 Unicode 编码)编写,则字节可能无法正确转换为字符.如果您认为这将是一个问题,则必须通过确定编码来处理该问题.搜索堆栈溢出以获取有关确定文件文本编码的信息.
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屋!