【发布时间】:2015-09-01 18:16:41
【问题描述】:
我正在尝试使用“|”读取文本文件数据分开,我使用下面的代码。尝试将数据表数据放入数据视图时,我能够在读取后从文本文件中读取数据我收到 '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)
【问题讨论】:
-
文件大小是多少?
-
异常行(完整跟踪)。问题很可能是文件大小或文件中的条目数超过列表中允许的最大项目数。
-
我正在尝试读取缺少 5 条记录的文本文件。
-
不是您问题的答案,但您应该真正使用数组的
Length属性,而不是Count()扩展方法。 -
你有多少列?
标签: c#