【发布时间】:2014-01-31 16:08:03
【问题描述】:
我是 C# 新手,我正在尝试读取 .csv 文件并将每一行文本放入单独的列表项中,以便稍后对其进行排序。
.csv 文件的组织方式如下:
1;"final60";"英国";"2013-12-06 15:48:16";
2;"donnyr8";"荷兰";"2013-12-06 15:54:32"; 等等
这是我的第一次尝试,但它不起作用。它在 Visual Studios 2010 中没有显示任何错误,但是当我运行控制台程序时,它显示以下异常而不是列表。
Exception of type 'System.OutOFMemoryException' was thrown. 这很奇怪,因为 .csv 文件只包含一个小列表。
try
{
// load csv file
using (StreamReader file = new StreamReader("file.csv"))
{
string line = file.ReadLine();
List<string> fileList = new List<string>();
// Do something with the lines from the file until the end of
// the file is reached.
while (line != null)
{
fileList.Add(line);
}
foreach (string fileListLine in fileList)
{
Console.WriteLine(fileListLine);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
那么我的处理方法正确吗?
【问题讨论】:
-
您应该真正使用 CSV 解析工具,而不是尝试自己动手。有足够多的边缘情况需要担心,不值得自己尝试全部处理。
标签: c# list file streamreader