![](/img/trans.png)
[英]Reading large file - System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown. in C#
[英]Exception of type 'System.OutOfMemoryException' was thrown while reading data from text file
我正在尝试使用“|”读取文本文件数据分开,我使用下面的代码。 当我尝试将数据表数据放入数据视图时,我能够在读取后从文本文件中读取数据我得到了“System.OutOfMemoryException”类型的异常被抛出,
任何人都可以建议我如何避免这种异常。
string filepath = System.Configuration.ConfigurationManager.AppSettings["data"];
if (filepath != "")
{
DataTable dt = new DataTable("file");
string[] columns1 = null;
var lines = File.ReadAllLines(filepath);
int Count = lines.Length;
//here taking columns and adding to table
if (lines.Count() > 0)
{
columns1 = lines[0].Split(new char[] { '|' });
foreach (var column in columns1)
dt.Columns.Add(column);
}
for (int i = 1; i < lines.Count(); i++)
{
DataRow dr = dt.NewRow();
string[] values = lines[i].Split(new char[] { '|' });
for (int j = 0; j < values.Count() && j < columns1.Count(); j++)
{
dr[j] = values[j];
}
}
dt.Rows.Add(dr);
DataView View = new DataView(dt);
//Here I m getting "Exception of type 'System.OutOfMemoryException' was thrown."
DataTable MD = View.ToTable("MD", false, "ID", "Description")
DataTable MM = View.ToTable("MM", false, "RecordNumber", "Item description")
if (MD.Rows.Count > 0)
{
InsertData(MD);
}
if (MM.Rows.Count > 0)
{
InsertData1(MM);
}
}
堆栈跟踪 :-
at System.Collections.Generic.List`1.set_Capacity(Int32 value)
at System.Collections.Generic.List`1.EnsureCapacity(Int32 min)
at System.Collections.Generic.List`1.Add(T item)
at System.Data.DataView.ToTable(String tableName, Boolean distinct, String[] columnNames)
多次使用 String.Split 可能会导致 OutOfMemoryException。 下载 Lumenworks Fast CSV 阅读器 - 问题已解决。 你会在这里得到它: http : //www.codeproject.com/Articles/9258/A-Fast-CSV-Reader
有关 Split 问题的更多详细信息,请查看以下链接:
http://vpchoudhary.blogspot.ie/2011/03/out-of-memory-exception-simple.html
string.split() 读取制表符分隔文件时出现“内存不足异常”
相关报价在这里:
当您对包含 1355049 个逗号分隔字符串的字符串进行拆分时会发生什么,每个字符串包含 16 个字符,总字符长度为 25745930 ?
指向字符串对象的指针数组:4(地址指针)*1355049 = 5420196(数组大小)+ 16(用于簿记)= 5420212的连续虚拟地址空间。 1355049个字符串的非连续虚拟地址空间,每个54字节. 这并不意味着所有这 130 万个字符串都将分散在整个堆中,但它们不会在 LOH 上分配。 GC 将在 Gen0 堆上的束上分配它们。 Split.Function 将创建大小为 25745930 的 System.Int32[] 内部数组,消耗(102983736 字节)~98MB 的 LOH,这是非常昂贵的 L。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.