System.OutOfMemoryException'从文本文件读取数据时抛出
本文关键字:数据 读取 文件 文本 OutOfMemoryException System | 更新日期: 2023-09-27 18:10:49
我试图读取一个文本文件数据与"|"分隔,我使用下面的代码。我能够从文本文件读取数据后,试图将数据表的数据放入数据视图,我得到异常类型'系统。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)
字符串的多种用途。分裂可能会导致OutOfMemoryException。下载Lumenworks快速CSV阅读器-问题解决了。您可以在这里获得:http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader
有关Split问题的更多详细信息,请查看以下链接:
http://vpnchoudhary.blogspot.ie/2011/03/out-of-memory-exception-simple.htmlstring.split() "内存不足"读取TAB分隔文件
时相关引用:
当您对包含1355049逗号的字符串进行分割时会发生什么每个16个字符的分隔字符串,具有总字符长度25745930 ?
指向string对象的指针数组:连续虚地址空间为4(地址指针)*1355049 = 5420196(数组大小)+ 16 (for簿记)= 5420212。的非连续虚拟地址空间1355049个字符串,每个54字节。它并不意味着所有的1.3数百万个字符串会分散在堆中,但它们会不能在LOH上分配。GC将在Gen0上按簇分配它们堆。分裂。函数将创建系统的内部数组。Int32[]的大小为25745930,消耗(102983736字节)~98MB的LOH,这是非常大的昂贵的l .