简体   繁体   English

文本文件阅读器仅读取第一行

[英]Text file reader only reads the first line

I'm trying to load every row in the text document into a list. 我正在尝试将文本文档中的每一行加载到列表中。 But for some reason, it only reads the first line and then exits. 但是由于某种原因,它只读取第一行,然后退出。

I have used this exact file reading method and it worked without any problems. 我已经使用了这种精确的文件读取方法,并且没有任何问题。 Now when I want to use it in the same way it doesn't work. 现在,当我想以相同的方式使用它时,它将无法正常工作。 I've tried different accounts of rows in the text document but it always exits the loop after the first row. 我尝试了文本文档中不同的行记录,但是它总是在第一行之后退出循环。

            //Reads the text file
        var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
        {
            //Adds the content of each line to a list
            string line;
            while ((line = streamReader.ReadLine()) != null)
            {
                destinationEmails.Add(line);
            }
        }

I Expect all lines to be read and put in the list. 我希望所有行都将被读取并放入列表中。

You should call ReadAllLines() to read all of the lines in the document. 您应该调用ReadAllLines()来读取文档中的所有行。 Update your code as following code. 按照以下代码更新您的代码。

    //Reads the text file
    var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

    using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
    {
        //Adds the content of each line to a list

        string line = string.Empty;

        while ((line = streamReader.ReadAllLines()) != null)
        {
            destinationEmails.Add(line);
        }
    }

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

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