【问题标题】:C# Reading a logfile into a listviewC# 将日志文件读入列表视图
【发布时间】:2012-06-22 15:53:52
【问题描述】:

我正在尝试导入一个日志文件并以网格格式(很像 excel)在列表视图中显示它。我想知道这可能是最好的方法。文件阅读器和数据表可能吗?我以前没有编写过这样的程序。这是一个窗体项目。

任何关于这个问题的建议都会很有帮助。

EDIT2:

日志文件示例:

 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
 i d   =   1 0 0 1
 P a r a m e t e r   1   =   E N A B L E D
 P a r a m e t e r   2   =   D I S A B L E D
 P a r a m e t e r   3   =   N U L L
 P a r a m e t e r   4   =   N U L L
 P a r a m e t e r   5   =   S U C C E S S  
 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 

这是使用不同数据的重复。

我希望将其读入并显示在不同标题 ID、名称等下的列表视图中

此应用程序也仅限于使用 .NET 3.5。

【问题讨论】:

  • 这是一个 WinForm 项目吗? WPF?日志文件的格式是什么?
  • 是的。抱歉,我更新了问题
  • 文件阅读器和数据表听起来不错,您的文件是否一致分隔?
  • 能否提供文件格式..
  • 我再次更新了问题。它是一个 .log 文件类型

标签: c# winforms listview datatable filereader


【解决方案1】:

我最好的猜测是使用StreamReader 一次读取一行文件并将数据放在DataGridView 中。

编辑:以下代码适用于针对 .Net 2.0 的项目,并假设您的 DataGridView 的名称是 dataGridView1

StreamReader reader = new StreamReader(@"C:\Users\jdudley\file.txt");
// Will be incremented every time ID shows up so it must started at -1 so we don't
// try and start inserting at 1.
int rowIndex = -1;
while (!reader.EndOfStream)
{
    string line = reader.ReadLine();
    string[] parsedLine = line.Split(new char[] { '=' });
    if(!this.dataGridView1.Columns.Contains(parsedLine[0]))
    {
        dataGridView1.Columns.Add(parsedLine[0],parsedLine[0]);
    }
    if (parsedLine[0].Trim().Equals("id"))
    {
        rowIndex++;
        dataGridView1.Rows.Add();
    }
    dataGridView1[parsedLine[0], rowIndex].Value = parsedLine[1];
}

【讨论】:

  • 这也是我的第一个猜测。不幸的是,我相信 DataGridView 是 .NET 4.0。我需要留在 3.5
  • 我在面向 2.0 的项目中使用 DataGridView
  • 如果是这样的话,我可能读错了。有人可以澄清一下吗?
  • 支持。这是3.5版本的文档msdn.microsoft.com/en-us/library/…你可以点击当前右侧的其他版本链接查看以前版本的文档。
  • 感谢您的代码。最后一行给我带来了麻烦。调试后似乎它在需要输入时跳过了最后一个 if 语句,因为 parsedLine[] 为空
【解决方案2】:

如果您尝试在日志文件中的每一行显示列表中的一行,我只需使用 File.ReadAllLines 来读取文件,然后使用字典来存储每个日志条目的键值对:

List<Dictionary<string, string>> entries = new List<Dictionary<string, string>>();
Dictionary<string, string> entry = null;
foreach (string line in File.ReadAllLines(logFilePath))
{
    string[] fields = line.Split('=');
    if (fields.Length > 1)
    {
        if (fields[0].Trim() == "id")
        {
            if (entry != null) entries.Add(entry);
            entry = new Dictionary<string, string>();
        }
        if (entry != null) entry[fields[0].Trim()] = fields[1].Trim();
    }
}
if (entry != null) entries.Add(entry);

【讨论】:

    猜你喜欢
    • 2016-02-03
    • 1970-01-01
    • 2022-12-29
    • 2012-03-08
    • 1970-01-01
    • 2023-03-31
    • 2012-04-06
    • 1970-01-01
    • 2016-07-02
    相关资源
    最近更新 更多