繁体   English   中英

如何将.csv文件的每一行分隔为字符串列表>

[英]How do I separate each line of a .csv file into a string list>

我是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);
}

我正在以正确的方式接近这个吗?

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

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

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

File.ReadLines - MSDN

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

如果您需要List<string>那么您可以:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM