2014-06-11 37 views
0

我正在使用流讀取器功能來搜索文本文件中的記錄,然後在控制檯窗口上顯示該記錄。它通過問題編號(1-50)搜索文本文件。它唯一使用的數字是問題1.它不會顯示任何其他問題,但它顯示問題1完美。以下是問題所在的代碼部分。爲什麼Streamreader只會提取第一個條目? c#

 static void Amending(QuestionStruct[] _Updating) 
    { 
     string NumberSearch; 
     bool CustomerNumberMatch = false; 
     Console.Clear(); 

    begin: 
     try 
     { 
      Console.Write("\t\tPlease enter the question number you want to append: "); 
      NumberSearch = Console.ReadLine(); 
      Console.ReadKey(); 
     } 
     catch 
     { 
      Console.WriteLine("Failed. Please try again."); 
      goto begin; 
     } 


     //finding the question number to replace 

     while (!CustomerNumberMatch) 
     { 
      var pathToCust = @"..\..\..\Files\questions.txt"; 

      using (StreamReader sr = new StreamReader(pathToCust, true)) 
      { 
       RecCount = 0; 

       questions[RecCount].QuestionNum = sr.ReadLine(); 


       if (questions[RecCount].QuestionNum == NumberSearch) 
       { 
        Console.Clear(); 

        Console.WriteLine("Question Number: {0}", questions[RecCount].QuestionNum); 

        questions[RecCount].Level = sr.ReadLine(); 
        Console.WriteLine("Level: {0}", questions[RecCount].Level); 

        questions[RecCount].Question = sr.ReadLine(); 
        Console.WriteLine("Question: {0}", questions[RecCount].Question); 

        questions[RecCount].answer = sr.ReadLine(); 
        Console.WriteLine("Answer: {0}", questions[RecCount].answer); 

        CustomerNumberMatch = true; 


       } 

       RecCount++; 

       //sr.Dispose(); 
      } 


     } 

回答

2

你每次都重新打開questions.txt文件在你while循環,所以它每次從文件的開頭開始,從來沒有闖過第一行(除非你正在尋找的問題1,當它將讀取問題的細節線)。相反,你需要循環的using聲明內:

var pathToCust = @"..\..\..\Files\questions.txt"; 
using (StreamReader sr = new StreamReader(pathToCust, true)) 
{ 
    while (!CustomerNumberMatch) 
    { 
     RecCount = 0; 
     questions[RecCount].QuestionNum = sr.ReadLine(); 
     if (questions[RecCount].QuestionNum == NumberSearch) 
     { 
      Console.Clear(); 
      Console.WriteLine("Question Number: {0}", questions[RecCount].QuestionNum); 

      questions[RecCount].Level = sr.ReadLine(); 
      Console.WriteLine("Level: {0}", questions[RecCount].Level); 

      questions[RecCount].Question = sr.ReadLine(); 
      Console.WriteLine("Question: {0}", questions[RecCount].Question); 

      questions[RecCount].answer = sr.ReadLine(); 
      Console.WriteLine("Answer: {0}", questions[RecCount].answer); 

      CustomerNumberMatch = true; 
     } 
     RecCount++; 
    } 
} 

東西還是顯得有點過的代碼 - 例如你只是在找到與NumberSearch匹配的問題時填充問題屬性,但希望這能讓你更接近。

+0

工作完美,好人! – COYG

相關問題