[Utility]自製吃一次檔案尾巴的小工具 Tail()

[Utility]自製吃一次檔案尾巴的小工具 Tail()

找了一下G大神, 似乎沒有馬上可套用的, 自己就寫一寫囉^^

真相細節就在程式的註解中, 請慢慢服用

   1:          /// <summary>
   2:          /// 吃一次檔案尾巴的小工具. (example: log file)
   3:          /// </summary>
   4:          /// @Author Hector Lee
   5:          /// @Since 2011/12/30
   6:          /// <param name="path">完整的檔案路徑</param>
   7:          /// <param name="lines">要吃幾行尾巴</param>
   8:          /// <param name="encoding">文字的編碼方式</param>
   9:          /// <returns>依編碼方式讀入的檔案尾巴文字</returns>
  10:          public static string Tail(string path, int lines, Encoding encoding)
  11:          {
  12:              string result = "";
  13:              // 暫存器
  14:              using (MemoryStream output = new MemoryStream()) 
  15:              {
  16:                  // 讀取器
  17:                  using (BufferedStream stream = new BufferedStream(new FileStream(path, FileMode.Open, FileAccess.Read)))
  18:                  {
  19:                      // move to before end
  20:                      stream.Seek(-1, SeekOrigin.End); 
  21:                      // read a byte
  22:                      int b = stream.ReadByte();
  23:   
  24:                      // 當達到最大行數時或讀到檔頭(b=-1)時
  25:                      for (int stack = lines; stack >= 0 && b > 0; )
  26:                      {
  27:                          // 寫入暫存器
  28:                          output.WriteByte((byte)b);
  29:   
  30:                          try
  31:                          {
  32:                              // 往前移2位, 然後讀1位. 
  33:                              stream.Seek(-2, SeekOrigin.Current);                             
  34:                              b = stream.ReadByte();
  35:                          }
  36:                          catch (IOException)
  37:                          {
  38:                              // 如果讀到檔頭, 就要離開迴圈了
  39:                              b = -1; 
  40:                          }
  41:   
  42:                          if (b == 10) // \n ascii code is 10 (lf) 13(cr)
  43:                          {
  44:                              // 如果讀到change line時,將尾巴就要少一條.
  45:                              stack--;  
  46:                          }
  47:   
  48:                      }
  49:                      // 暫存器吐出到陣列, 然後倒序回來(因為是從尾巴讀起)
  50:                      byte[] bytes = output.ToArray();
  51:                      Array.Reverse(bytes);
  52:                      // 依編碼方式轉成字串
  53:                      result = encoding.GetString(bytes);
  54:                  }
  55:              }
  56:   
  57:              return result;
  58:          }