domenica 1 maggio 2016

Leggere un file di log al contrario in c#

In un'applicazione web in ambiente .Net è possibile leggere al contrario un file di log in formato testo (alimentato in modalità 'append'), ossia dalla fine all'inizio.
Può capitare che il file venga utilizzato da un altro processo, in questo esempio copio il file in un altro dello stesso tipo e lo apro per leggerlo.

//Create .aspx file; this is code-behind .cs

protected void Page_Load(object sender, EventArgs e)
{
 strLog = new StringBuilder("");
 try
 {
  //directory log on webapp
  string pathLogOriginale = Server.MapPath("~/logs/log.txt");

  //If the file used by another process, I copy the file and then I read it
  File.Copy(pathLogOriginale, Server.MapPath("~/logs/log_copy.txt"), true);
  string pathLog = Server.MapPath("~/logs/log_copy.txt");

  //example only 100 rows
  foreach (var line in File.ReadLines(pathLog).Reverse().Take(100)) //only the first 100 rows
 	strLog.Append(line+"<br><br>");

  /*
   * use string strLog in .aspx file in label object or text object
   */
 } 
 catch (Exception ex)
 {
 }
}