我正在使用流阅读器功能在文本文件中搜索记录,然后在控制台窗口中显示该记录。它正在通过问题编号(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();
}
}
答案 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
匹配时,您只填充问题属性,但希望这会让您更接近。