Solved

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

Posted on 2016-09-27
5
61 Views
Last Modified: 2016-09-28
We know to read all lines of a text can be done in asp.net 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
0
Comment
Question by:Alex E.
5 Comments
 
LVL 49

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.
0
 
LVL 62

Accepted Solution

by:
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

0
 
LVL 33

Expert Comment

by:it_saige
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))
						_questions.Add(_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))
						_question.Answers.Add(_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))
					{
						_question.Answers.Add(_answer);
						_answer = default(Answer);
					}
				}
			}

			// Sanity check
			if (_question != default(Question))
				_questions.Add(_question);

			foreach (var q in _questions)
			{
				Console.WriteLine("Question {0}:  {1}", _questions.IndexOf(q) + 1, q);
				Console.WriteLine("Answers:");
				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();
				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");
				Console.WriteLine();
			}
			Console.ReadLine();
		}
	}

	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
-saige-
1
 

Author Closing Comment

by:Alex E.
ID: 41820025
Thank you
0
 
LVL 62

Expert Comment

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

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

863 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now