How to read last “n” lines of log file

前端 未结 7 1233
轮回少年
轮回少年 2020-12-03 14:24

need a snippet of code which would read out last \"n lines\" of a log file. I came up with the following code from the net.I am kinda new to C sharp. Since the log file migh

7条回答
  •  天涯浪人
    2020-12-03 15:05

    A friend of mine uses this method (BackwardReader can be found here):

    public static IList GetLogTail(string logname, string numrows)
    {
        int lineCnt = 1;
        List lines = new List();
        int maxLines;
    
        if (!int.TryParse(numrows, out maxLines))
        {
            maxLines = 100;
        }
    
        string logFile = HttpContext.Current.Server.MapPath("~/" + logname);
    
        BackwardReader br = new BackwardReader(logFile);
        while (!br.SOF)
        {
            string line = br.Readline();
            lines.Add(line + System.Environment.NewLine);
            if (lineCnt == maxLines) break;
            lineCnt++;
        }
        lines.Reverse();
        return lines;
    }
    

提交回复
热议问题