为什么streamreader只获得第一个条目? C#

时间:2014-06-11 22:26:47

标签: c# search streamreader

我正在使用流阅读器功能在文本文件中搜索记录,然后在控制台窗口中显示该记录。它正在通过问题编号(1-50)搜索文本文件。它使用的唯一数字是问题1.它不会显示任何其他问题,但它显示问题1完美。以下是问题所在代码的一部分。

        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();
            }


        }

1 个答案:

答案 0 :(得分: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匹配时,您只填充问题属性,但希望这会让您更接近。