Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » C# reading text into 2D array

This thread is locked; no one can reply to it. rss feed Print
C# reading text into 2D array
Jeffsg605
Member #13,048
July 2011

Sorry to post an XNA question here but I can't find the answer to this anywhere including XNA and C# forums.

Does anybody know how to read a text file into a 2D array in C#. I have this:

            int[,] map;
            FileStream fileStream = new FileStream(@"Map.txt", FileMode.Open);
            map = new int[5,5];
            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    map[i,j] = // what goes here?
                }
            }

Any direction is much appreciated.
Thanks!

james_lohr
Member #1,947
February 2002

What are you trying to read from your file? - if it is simply an array of chars:

#SelectExpand
1var width = 5; 2var height = 5; 3var map = new char[width,height]; 4var file = new StreamReader("Map.txt"); 5string line; 6var lineCount = 0; 7while((line = file.ReadLine()) != null) 8{ 9 if(lineCount<height){ 10 for(int i=0;i<width && i < line.Length){ 11 map[i,lineCount] = line[i]; 12 } 13 } 14 lineCount++; 15} 16 17file.Close();

If it is an array of integers, then you will need to split it by some separator per line, and parse the individual integers.

bamccaig
Member #7,536
July 2006
avatar

Jeffsg605
Member #13,048
July 2011

Actually yeah, an array of chars was fine. I was focusing on reading ints and having a lot of trouble but chars did the job just fine. It was a lot of unnecessary frustration.

Thanks guys!

Go to: