C# reading text into 2D array
Jeffsg605

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

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

Show us an example file.

Jeffsg605

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!

Thread #609012. Printed from Allegro.cc