0

我读取了文本文件并显示在DataGridView数据正在显示中,但是在上面的文本文件中与日志文件有关,我想按月显示该日志文件DataTable,如果可能的话,不使用 .

private void BtnUser_Click(object sender, EventArgs e)
{
  dgv1.Columns.Add("col1", "Ipaddress");
  dgv1.Columns.Add("col2", "Sysname");
  dgv1.Columns.Add("col3", "username");
  dgv1.Columns.Add("col4", "text");
  dgv1.Columns.Add("col5", "datetime");

  string line;
  StreamReader strRead = new StreamReader("D:\\login.lgl");
  {
    int row = 0;

    while ((line = strRead.ReadLine()) != null)
    {
      string[] columns = line.Split('|');
      dgv1.Rows.Add();
      for (int i = 0; i < columns.Length; i++)
      {
        dgv1[i, row].Value = columns[i];
      }
      row++;
    }
  }
}
4

2 回答 2

1

您可以使用 Linq 按月分组:

var logMonthGroups = File.ReadLines("D:\\login.lgl")
    .Select(l => new { Cols = l.Split('|') })
    .Select(x => new
    {
        Ipaddress = x.Cols.ElementAtOrDefault(0),
        Sysname = x.Cols.ElementAtOrDefault(1),
        username = x.Cols.ElementAtOrDefault(2),
        text = x.Cols.ElementAtOrDefault(3),
        datetime = x.Cols.ElementAtOrDefault(4) == null ? DateTime.MinValue : DateTime.Parse(x.Cols[4])
    })
    .GroupBy(x => new { Year = x.datetime.Year, Month = x.datetime.Month })
    .OrderBy(g => g.Key.Year).ThenBy(g => g.Key.Month);

foreach(var group in logMonthGroups)
{
    // add to the DataGridView ...
}
于 2013-01-21T11:59:56.017 回答
1

我建议您为从文件中解析的结构创建一个类,例如:

public class LogFileItem
{
   public string IpAddress {get; set;}
   public string Sysname {get; set;}
   public string Username {get; set;}
   public string Text {get; set;}
   public DateTime DateTime {get; set;}

   public static List<LogFileItem> ParseLogFile(string path)
   {
     List<LogFileItem> result = new List<LogFileItem>();

     //in a real scenario, this code should have a lot more error checks
     string line;
     StreamReader strRead = new StreamReader(path);

     while ((line = strRead.ReadLine()) != null)
     {
       string[] columns = line.Split('|');

       LogFileItem item = new LogFileItem();
       item.IpAddress = columns[0];
       item.Sysname = columns[1];
       item.Username = columns[2];
       item.Text = columns[3];
       //this assumes that the dateTime column is parsable by .net
       item.DateTime = DateTime.Parse(columns[4]);

       result.add(item); 
     }
     return result;
   }

}

那么你可以这样做:

private void BtnUser_Click(object sender, EventArgs e)
{
   List<LogFileItem> logItems = LogFileItem.ParseLogFile(@"D:\login.lgl");
   dgv1.DataSource = logItems;
}

来显示数据。您也可以按照您想要的任何方式过滤数据,如果您有month/year对过滤,您可以这样做:

   List<LogFileItem> logItems = LogFileItem.ParseLogFile(@"D:\login.lgl");
   var logsPerMonth = logItems.Where(li => li.DateTime.Year = year && li.DateTime.Month == month);

请注意,日期时间解析在某种程度上是一种黑暗艺术,因此您可以查看一下DateTime.ParseExact以使其工作。另外,看看使用using 语句,或从文本文件中读取行File.ReadAllLines

于 2013-01-21T12:18:43.277 回答