c# - 在 C# 中读取大日志文件

标签 c# streamreader logfiles

对于我的项目,我需要从日志文件中提取消息类型。我有一个 700 MB 的日志文件,其中包含大约 470 万行,我需要逐行读取每个条目并提取消息字段。我需要找到每个条目中消息的大小(即事件大小)并将其与该消息一起存储在字典中。相同的事件大小可以有多个消息。但是当我使用以下逻辑时,我得到了 OutOfMemoryException 。

Dictionary<Int32,List<String>> dt=new Dictionary<Int32,List<String>>();
List<String> entries=new List<String>();
StreamReader sr=new StreamReader("Bluegene.log");
String s;
while((s=sr.readLine())!=null)
{
    eventsize=s.length - 9; //size of only the message field
    entries.Add(s);
    if (!dt.ContainsKey(eventsize))
    {
        dt.Add(eventsize, entries);
    }
    else
    {
       dt.Remove(eventsize);
       dt.Add(eventsize, entries);
     }
  }

使用 MemoryMappedFile 有帮助吗?

最佳答案

问题是您的列表不断增长。
因此,您可以尝试以下操作:

Dictionary<Int32, List<String>> dt = new Dictionary<Int32, List<String>>();           
            int eventsize;
            StreamReader sr = new StreamReader("Bluegene.log");           
            string s;
            while ((s = sr.ReadLine()) != null)
            {
                eventsize = s.Length - 9; //size of only the message field      
                if (!dt.ContainsKey(eventsize))
                {
                    List<String> entries = new List<String>();
                    entries.Add(s);
                    dt.Add(eventsize, entries);
                }
                else
                {
                    dt[eventsize].Add(s);
                }
            }

关于c# - 在 C# 中读取大日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18680254/

相关文章:

c# - System.Linq.Dynamic.DynamicExpression 用方法解析表达式

c# - 如何遍历 SortedList,获取键和值

c# - 如何将文件中的项目读入项目列表并将属性设置为文件中的值?

c# - 如何在 C# 中添加外部文件的数据量(流读取器)

c# - Azure Function 找不到文档 openXML

c# - 尝试用 WinRT 中的绑定(bind)替换文件时访问被拒绝

c# - 如何读取字节和字符串的混合文件

linux - 如何查看文件更新内容的全部部分

hadoop - 插入Hive表

bash - 我如何使用 bash (grep/sed/etc) 在两个时间戳之间获取日志文件的一部分?