C#跳过readlines

时间:2016-02-21 19:12:16

标签: c# while-loop

我有一个读取文件的While循环。问题是它读取1行,然后跳过1行,读取,跳过等等。 我无法弄清楚是什么导致它跳过。如果有人能告诉我'那太棒了(:

StreamReader sentencesFile = new StreamReader(@"C:\Users\Jeroen\Desktop\School\C#\opwegmetcsharp\answersSen.txt");
string line;

while ((line = sentencesFile.ReadLine()) != null)
{
    string SentenceFileString = sentencesFile.ReadLine();
    string keyWords = line.Substring(0, line.IndexOf(' '));
    string sentence = line.Substring(line.IndexOf(' ') + 1);
    string testOutput= keyWords + sentence;
}

2 个答案:

答案 0 :(得分:8)

您正在阅读while循环条件内的行。你不需要再次阅读它作为循环中的第一个语句。

while ((line = sentencesFile.ReadLine()) != null)
{
    string SentenceFileString = line;  // can be removed
    string keyWords = line.Substring(0, line.IndexOf(' '));
    string sentence = line.Substring(line.IndexOf(' ') + 1);
    string testOutput = keyWords + sentence;
}

答案 1 :(得分:2)

问题在于:

while ((line = sentencesFile.ReadLine()) != null)
{
    string SentenceFileString = sentencesFile.ReadLine();

当你要求换行!= null你已经读了一行, 这将再次跳过

string SentenceFileString = sentencesFile.ReadLine();

soution:

注释掉第二行(你甚至不使用变量SentenceFileString)并继续使用while

while ((line = sentencesFile.ReadLine()) != null)
{

    string keyWords = line.Substring(0, line.IndexOf(' '));
    string sentence = line.Substring(line.IndexOf(' ') + 1);
    string testOutput= keyWords + sentence;
}