crm*_*ham 2 c# file list streamreader
我是c#的新手,我正在尝试读取.csv文件并将每行文本放入一个单独的列表项中,以便稍后对其进行排序.
.csv文件的组织方式如下:
1;"final60";"英国";"2013-12-06 15:48:16";
2;"donnyr8";"荷兰";"2013-12-06 15:54:32"; 等等
这是我的第一次尝试不起作用.它在Visual Studio 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);
}
Run Code Online (Sandbox Code Playgroud)
我正在以正确的方式接近这个吗?
如果您加载的文件不是很大,那么您可以使用File.ReadAllLines:
List<string> list = File.ReadAllLines("file.csv").ToList();
Run Code Online (Sandbox Code Playgroud)
正如Servy在评论中指出的那样,最好使用File.ReadLines方法.
ReadLines和ReadAllLines方法的不同之处如下:使用ReadLines时,可以在返回整个集合之前开始枚举字符串集合; 当您使用ReadAllLines时,必须等待返回整个字符串数组才能访问该数组.因此,当您使用非常大的文件时,ReadLines可以更高效.
如果您需要,List<string>那么您可以这样做:
List<string> list = File.ReadLines("file.csv").ToList();
Run Code Online (Sandbox Code Playgroud)
您没有更新line变量,因此该行总是与null无限循环不同而导致OutOfMemoryException
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);
line = file.ReadLine();
}
foreach (string fileListLine in fileList)
{
Console.WriteLine(fileListLine);
}
}
}
Run Code Online (Sandbox Code Playgroud)
但正确的方法将是
List<string> list = File.ReadLines("file.csv").ToList();
Run Code Online (Sandbox Code Playgroud)
这比File.ReadAllLines以下原因
更好从MSDN:
When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned;
| 归档时间: |
|
| 查看次数: |
860 次 |
| 最近记录: |