[Solved] Reading a text file and assigning certain lines to certain variables [closed]


Because all your data is in the same file, your going to need to take a slightly different approach. Instead of passing in the item to fill out, I would have the function return the list of read questions:

public IEnumerable<QuestionUnit> ReadQuestionFile()

Then, read in a loop until you reach the end of the file. This approach is NOT safe for invalid input, so be careful:

string fileName = "TextFile1.txt";
List<QuestionUnit> readQuestions = new List<QuestionUnit>();
using (StreamReader myReader = new StreamReader(fileName))
{
    while (!myReader.EndOfStream)
    {
        QuestionUnit newQuestion = new QuestionUnit();
        newQuestion.M_Question  = myReader.ReadLine();
        newQuestion.M_Answers = myReader.ReadLine();
        newQuestion.M_CorrectAnswers = myReader.ReadLine();
        newQuestion.M_Explanation = myReader.ReadLine();

        readQuestions.Add(newQuestion);
    }
}
return readQuestions;

Basically, you read until the end of the file, reading four lines at a time. You’ll get some null values if the input format isn’t correct. You don’t really need an array here since you can store the values directly in your object, which you then add to the list when you are done populating it (technically you could have done it before as well). Then you return the filled out list to whatever uses it.

You could possibly use a yield return instead of directly adding to a list, but that is a bit of an advanced concept for starting out, and I’m not sure how well it would mesh with the File I/O. It is good to be aware of its existence either way. The only change would be the removal of readQuestions, and the line:

yield return newQuestion;

where the call to Add currently is.

Let me know if I can clarify anything!

8

solved Reading a text file and assigning certain lines to certain variables [closed]