【问题标题】:How do I separate each line of a .csv file into a string list>如何将 .csv 文件的每一行分隔成一个字符串列表>
【发布时间】: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


【解决方案1】:

如果您正在加载的文件不是很大,那么您可以使用File.ReadAllLines:

List<string> list = File.ReadAllLines("file.csv").ToList();

正如 Servy 在评论中指出的那样,最好使用 File.ReadLines 方法。

File.ReadLines - MSDN

ReadLines 和 ReadAllLines 方法的区别如下: ReadLines,可以开始枚举之前的字符串集合 整个集合被退回;当您使用 ReadAllLines 时,您必须 等待返回整个字符串数组,然后才能访问 数组。因此,当您处理非常大的文件时, ReadLines 可以更高效。

如果您需要List&lt;string&gt;,那么您可以这样做:

List<string> list = File.ReadLines("file.csv").ToList();

【讨论】:

  • 您应该在此处使用ReadLines 而不是ReadAllLines 以避免构造不需要的数组的开销。理想情况下,可以删除 ToList 以允许数据流传输,而不是急切加载整个文件。
  • +1 用于更新答案和处理贡献。
【解决方案2】:

您没有更新 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);
             }
           }
    }

但正确的方法是

List<string> list = File.ReadLines("file.csv").ToList();

File.ReadAllLines更好,原因如下 来自MSDN

When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned;

【讨论】:

    【解决方案3】:

    您应该使用File.ReadAllLines(),然后解析数组中的字符串。 对于非常大的文件,这可能不可行,您必须将单行流式传输并一一处理。 但这是您只有在看到这种快速方法惨遭失败后才能决定的事情。在那之前,坚持快速和肮脏。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-15
      • 2011-12-26
      • 1970-01-01
      • 2019-03-20
      • 2019-02-26
      • 1970-01-01
      • 2020-11-29
      • 2017-04-23
      相关资源
      最近更新 更多