StreamReader 读取大文件报错OutOfMemoryException

newnazi 2013-11-27 08:00:56
我写了 一段代码读取解析文件内容如下,被读取的文件的大约780M 读到845715行的时候提示错误
此时PC内存使用高达2G,请问如何解决或者可用其他方式读取 大文件?

ArrayList oldFileList=new ArrayList(2000);
StreamReader reader = new StreamReader(filepath, Encoding.GetEncoding("gb2312"));
string n1 = string.Empty;

try
{
while (reader.Peek() > -1)
{
str = reader.ReadLine(); // 这里报错

if (str.Length > 5)
{
n1 = str.Substring(0, 4);
if (n1 == "A1")
{
oldFileList.Add(str);
}
else if (n1 == "B1")
{
oldFileList.Add(str);
}
}
str = null;
n1 = null;
iCount++;

if (iCount % 100 == 0)
{
GC.Collect();
}
}

}

catch (Exception ex)
{
throw ex;
}
finally
{
reader.Close();
reader.Dispose();
}
return oldFileList;


引发类型为“System.OutOfMemoryException”的异常。
...全文
541 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
newnazi 2014-06-02
  • 打赏
  • 举报
回复
引用 3 楼 bdmh 的回复:
我还是建议用内存映射读取大文件
没有试 以后有时间再搞
newnazi 2014-06-02
  • 打赏
  • 举报
回复
引用 1 楼 wind_cloud2011 的回复:
用stream实现分块读取 http://bbs.csdn.net/topics/350230269
这个方法试了 成功
bdmh 2013-11-28
  • 打赏
  • 举报
回复
我还是建议用内存映射读取大文件
wind_cloud2011 2013-11-28
  • 打赏
  • 举报
回复
ArrayList oldFileList=new ArrayList(2000); 是不是这里值设得太小有关? ArrayList oldFileList=new ArrayList();默认的看一下
wind_cloud2011 2013-11-28
  • 打赏
  • 举报
回复
用stream实现分块读取 http://bbs.csdn.net/topics/350230269

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧