read lines of text file and put each row in mutliple variables c#

Posted on 2016-09-27
Last Modified: 2016-09-28
We know to read all lines of a text can be done in c# with:

string contents = File.ReadAllText(@"C:\temp\test.txt")

Open in new window

In the text files we have something similar like this:

var p1='Question 1'
var a1a='Answer1 1'
var a1b='Answer1 2'
var a1c='Answer1 3'
var a1d='Answer1 4'
var e1a='Incorrect'
var e1b='Incorrect'
var e1c='Incorrect'
var e1d='Correct'
var p2='Question 2'
var a2a='Answer2 1'
var a2b='Answer2 2'
var a2c='Answer2 3'
var a2d='Answer2 4'
var e2a='Correct'
var e2b='Incorrect'
var e2c='Incorrect'
var e2d='Incorrect'
var p3='Question 3'
var a3a='Answer3 1'
var a3b='Answer3 2'
var a3c='Answer3 3'
var a3d='Answer3 4'
var e3a='Correct'
var e3b='Incorrect'
var e3c='Incorrect'
var e3d='Incorrect'
var p4='Question 4'
var a4a='Answer4 1'
var a4b='Answer4 2'
var a4c='Answer4 3'
var a4d='Answer4 4'
var e4a='Correct'
var e4b='Incorrect'
var e4c='Incorrect'
var e4d='Incorrect'
var p5='Question 5'
var a5a='Answer5 1'
var a5b='Answer5 2'
var a5c='Answer5 3'
var a5d='Answer5 4'
var e5a='Correct'
var e5b='Incorrect'
var e5c='Incorrect'
var e5d='Incorrect'
var p6='Question 6'
var a6a='Answer6 1'
var a6b='Answer6 2'
var a6c='Answer6 3'
var a6d='Answer6 4'
var e6a='Correct'
var e6b='Incorrect'
var e6c='Incorrect'
var e6d='Incorrect'
var p7='Question 7'
var a7a='Answer7 1'
var a7b='Answer7 2'
var a7c='Answer7 3'
var a7d='Answer7 4'
var e7a='Correct'
var e7b='Incorrect'
var e7c='Incorrect'
var e7d='Incorrect'
var p8='Question 8'
var a8a='Answer8 1'
var a8b='Answer8 2'
var a8c='Answer8 3'
var a8d='Answer8 4'
var e8a='Correct'
var e8b='Incorrect'
var e8c='Incorrect'
var e8d='Incorrect'
var p9='Question 9'
var a9a='Answer9 1'
var a9b='Answer9 2'
var a9c='Answer9 3'
var a9d='Answer9 4'
var e9a='Correct'
var e9b='Incorrect'
var e9c='Incorrect'
var e9d='Incorrect'
var p10='Question 10'
var a10a='Answer10 1'
var a10b='Answer10 2'
var a10c='Answer10 3'
var a10d='Answer10 4'
var e10a='Correct'
var e10b='Incorrect'
var e10c='Incorrect'
var e10d='Incorrect'

Open in new window

How can we do to put each row in the variable that correspond from the txt file. For example the first line has p1='Question 1' and then is needed to store in code behind in a string variable called "p1" the value "Question 1" in other example the second line has var a1a='Answer1 1' then code behind must store the string variable with the name "a1a" and with the value "Answer 1 1" and so on for each row of the text file.

What code can be used to do that after read all the lines with like described before (File.ReadAllText)?

Thank you
Question by:Alex E.
LVL 50

Expert Comment

by:Ryan Chong
ID: 41819115
For example the first line has p1='Question 1' and then is needed to store in code behind in a string variable called "p1" the value "Question 1" in other example the second line has var a1a='Answer1 1' then code behind must store the string variable with the name "a1a" and with the value "Answer 1 1" and so on for each row of the text file.

Since you can't define a variable name dynamically (as far as what I know), you probably can define a class instead, and store the variable name and its value accordingly.

what you need to do is to parse the content of the file.
LVL 63

Accepted Solution

Fernando Soto earned 500 total points
ID: 41819155
Hi Alex;

You could load the data into a Dictionary<string, string> where the key is the variable name and the value is the string value, something like the following code snippet.
List<string> contents = File.ReadAllLines(@"C:\Working Directory\test.txt").ToList();
Dictionary<string, string> vars = new Dictionary<string, string>();
foreach( string line in contents ) {
    string[] parts = line.Split(new char[] {'='}, StringSplitOptions.RemoveEmptyEntries);
    string key = parts[0].Substring(4).Trim();
    string value = parts[1].Replace("'", "").Trim();
    vars.Add ( key, value );

Open in new window

LVL 33

Expert Comment

ID: 41820024
I am not certain as to what your ultimate goal is, but assuming that you are wanting to create a question/answer list, you could (as Ryan suggested) use a distinct object that represents a question.  This object will have properties.  Into these properties we could load the associated values from your text files.  It just comes down to parsing.

Here is one example using the text file you have presented:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace EE_Q28972873
	class Program
		static Questions _questions = new Questions();
		static void Main(string[] args)
			var _contents = (from line in File.ReadAllLines("test.txt")
						  select line.Replace("var ", "").Replace("'", "").Split(new[] { "=" }, StringSplitOptions.None)).ToDictionary(k => k[0], v => v[1], StringComparer.OrdinalIgnoreCase);

			Question _question = default(Question);
			Answer _answer = default(Answer);
			foreach (var pair in _contents)
				if (pair.Key.StartsWith("p", StringComparison.OrdinalIgnoreCase))
					if (_question != default(Question))
					_question = new Question() { Text = pair.Value, Answers = new List<Answer>() };
				else if (pair.Key.StartsWith("a", StringComparison.OrdinalIgnoreCase) && _question != default(Question))
					if (_answer != default(Answer))
					_answer = new Answer() 
						Text = pair.Value, 
						IsCorrect = _contents[string.Format("e{0}", pair.Key.Substring(1))].IndexOf("incorrect", StringComparison.OrdinalIgnoreCase) == -1 
				else if (pair.Key.StartsWith("e", StringComparison.OrdinalIgnoreCase) && _answer != default(Answer))
					if (_answer != default(Answer))
						_answer = default(Answer);

			// Sanity check
			if (_question != default(Question))

			foreach (var q in _questions)
				Console.WriteLine("Question {0}:  {1}", _questions.IndexOf(q) + 1, q);
				foreach (var a in q.Answers)
					Console.WriteLine("{0}.  {1}", (char)(65 + q.Answers.IndexOf(a)), a);

				Console.Write("Select A, B, C or D:");
				var selected = Console.ReadKey().KeyChar;
				Console.WriteLine("{0}!!!", (from e in q.Answers where selected.Equals((char)(65 + q.Answers.IndexOf(e))) || selected.Equals((char)(97 + q.Answers.IndexOf(e))) select e).FirstOrDefault().IsCorrect ? "Correct" : "Incorrect");

	class Questions : List<Question>
		public Questions() { ;}
		public Questions(int capacity) : base(capacity) { ;}
		public Questions(IEnumerable<Question> collection) : base(collection) { ;}

	class Question
		public string Text { get; set; }
		public List<Answer> Answers { get; set;}

		public override string ToString()
			return Text;

	class Answer
		public string Text { get; set; }
		public bool IsCorrect { get; set; }

		public override string ToString()
			return Text;

Open in new window

Produces the following output -Capture.JPG

Author Closing Comment

by:Alex E.
ID: 41820025
Thank you
LVL 63

Expert Comment

by:Fernando Soto
ID: 41820085
Not a problem Alex, glad to help.

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question