SexySaxMan
SexySaxMan

Reputation: 13

C# Read from text file separated by commas into 2d array

I currently have this:

using (StreamReader sr = new StreamReader("answers.txt"))
{
    for (iCountLine = 0; iCountLine < 10; iCountLine++)
    {
         for (iCountAnswer = 0; iCountAnswer < 4; iCountAnswer++)
         {
             sQuestionAnswers[iCountLine, iCountAnswer] = 
         }
    }
}

My text file is formatted like this (10 lines of text, with 4 items on each line separated by commas):

example, example, example, example 
123, 123, 123, 123

I'm not sure what I need after the "=" in the for loop to get it to read and split the contents of the text file into the 2D array.

Upvotes: 1

Views: 11688

Answers (4)

Ivan Golović
Ivan Golović

Reputation: 8832

This doesn't use StreamReader, but it's short and easy to understand:

        string[] lines = File.ReadAllLines(@"Data.txt");
        string[][] jaggedArray = lines.Select(line => line.Split(',').ToArray()).ToArray();

Rows are extracted by ReadAllLines according to newline. Columns values are extracted by calling Split on every line. It returns jagged array that you can use similarly to multidimensional array, also jagged arrays are generally faster than multidimensional arrays.

Upvotes: 2

Artak
Artak

Reputation: 2887

I'd suggest you to change the approach.

Go over the file using ReadLine() method of a StreamReader class. Then split the read line using Split(new[]{','}), and this will give you every single record. And finally the sQuestionAnswers[iCountLine, iCountAnswer] will be: the just Split array's [iCountAnswer]'s record.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726549

I'm not sure what I need after the "=" in the for loop

There's also a line missing above it:

var tokens = sr.ReadLine().Split(',');

Now the line with = would look like this:

sQuestionAnswers[iCountLine, iCountAnswer] = tokens[iCountAnswer];

Upvotes: 2

Kevin Holditch
Kevin Holditch

Reputation: 5303

string line;

using (var sr = new StreamReader("answers.txt"))
{
    while ((line = sr.ReadLine()) != null)
    {
        for (int iCountLine = 0; iCountLine < 10; iCountLine++)
        {
            var answers = line.Split(',');
            for (int iCountAnswer = 0; iCountAnswer < 4; iCountAnswer++)
            {
                sQuestionAnswers[iCountLine, iCountAnswer] = answers[iCountAnswer];
            }
        }
    }
}

Upvotes: 0

Related Questions