如何阅读文本文件

时间:2013-01-21 11:48:09

标签: c# datagridview

我读了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++;
    }
  }
}

2 个答案:

答案 0 :(得分: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 ...
}

答案 1 :(得分: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 statement,或使用File.ReadAllLines读取文本文件中的行。