日期:2014-05-19  浏览次数:20906 次

有什么方法可以快速读取文本文件最后10行.
程序每天生成一个Log.txt文件,并且一般在700k左右,程序查看Log.txt的时候会很慢,所以有没有办法只返回Log.txt最后10行的信息哪?

------解决方案--------------------
用ifilter 读取最后的一段字符串
------解决方案--------------------
private void button1_Click(object sender, EventArgs e)
{
FileStream vFileStream = new FileStream(@ "c:\temp\temp.log ",
FileMode.Open, FileAccess.Read);
byte[] vBuffer = new byte[0x1000];
int vReadLength;
int vLineCount = 0;
int vReadCount = 0;
int j = 0;
do
{
vFileStream.Seek(-vBuffer.Length * ++vReadCount, SeekOrigin.End);
vReadLength = vFileStream.Read(vBuffer, 0, vBuffer.Length);
for (int i = vReadLength - 1; i > = 0; i--)
{
j++;
if (vBuffer[i] == 10) vLineCount++;
if (vLineCount > = 9)
{
if (vReadCount > 1)
{
vBuffer = new byte[vFileStream.Length - j - 1];
vFileStream.Seek(j, SeekOrigin.End);
vReadLength = vFileStream.Read(vBuffer, 0, vBuffer.Length);
j = 0;
}
textBox1.Text = Encoding.Default.GetString(vBuffer, vReadLength - j, j);
break;
}
}
} while (vLineCount < 9 || vReadLength < vBuffer.Length);
if (vLineCount < 9)
textBox1.Text = Encoding.Default.GetString(vBuffer, 0, vReadLength);
vFileStream.Close();
Text = vLineCount.ToString();
}

------解决方案--------------------
TextReader reader = new StreamReader(fullPathname);
string line;
while ((line = reader.ReadLine()) != null)
{
this.textBox1.Text += line + "\n ";
}
reader.Close();

//再加下面两句,直接滚动到最下面:
this.textBox1.SelectAll();
this.textBox1.ScrollToCaret();