首页  编辑  

读日志的最后几行

Tags: /C#/文件目录操作/   Date Created:

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();