Solved

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

Posted on 2016-09-27
5
90 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.
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 Comments
 
LVL 52

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 63

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 34

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 63

Expert Comment

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

Featured Post

Is Your DevOps Pipeline Leaking?

Is your CI/CD pipeline a hodge-podge of randomly connected tools? You’ve likely got a tool to fix one problem & then a different tool to fix another, resulting in a cluster of tools with overlapping functionality. Learn how to optimize your pipeline with Gartner's recommendations

Question has a verified solution.

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

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…

734 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