0

I want to read a 30x30 2-dimensional array containing commas from a text file and assign it to a two-dimensional array. How do I do this in C#?

Content of my text file:

1, 0, 1, 1, 1
1, 1, 0, 1, 0
1, 0, 1, 0, 0
0, 0, 1, 1, 1 

It continues like this. It has 30 rows and 30 columns.

  • It's old question. Read this: [enter link description here](https://stackoverflow.com/questions/13724781/2d-array-from-text-file-c-sharp) – Nika May 15 '22 at 16:18
  • Does this answer your question? [2d Array from text file c#](https://stackoverflow.com/questions/13724781/2d-array-from-text-file-c-sharp) – burnsi May 20 '22 at 19:43

1 Answers1

0
StreamReader streamReader = new StreamReader("Path/To/File.txt");
int[,] myMatrix = new int[30, 30];
for (int row = 0; row < 30; row++)
{
    int[] line = streamReader.ReadLine().Split(", ").Select(int.Parse).ToArray();
    for (int col = 0; col < 30; col++)
    {
        myMatrix[row, col] = line[row];
    }
}
John
  • 11
  • 4
  • I applied these code pieces but there is an error: System.FormatException 'input string was not in a correct format.' – user19108367 May 15 '22 at 18:08
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 16 '22 at 04:48
  • On what line did you get the error? The code works for me. – John May 16 '22 at 08:15