"Index was outside the bounds of the array."

July 3, 2009 by admin
Filed under: Xbox360 News 

I'm trying to read a text file and store it into an array, then draw a map according to the contents of the file. The file contents are:

5
7
2000002
2000002
2111112
2222222
2222222
I'm using this code to read the file, then draw it:
1 public void InitializeReadMaps(int map) // this is just run once, it's just a test  
2 {  
3     this.FileName = "map" + map.ToString() + ".txt";  
4     this.file = new FileStream(this.FileName, FileMode.Open, FileAccess.Read);  
5     this.sr = new StreamReader(this.file);  
6     string line = this.sr.ReadLine();  
7     this.YLength = Int32.Parse(line);  
8     this.XLength = Int32.Parse(line);  
9     this.map = new char[this.XLength, this.YLength];  
10 }  
11   
12 public void ReadMaps()  
13 {  
14     if (!sr.EndOfStream)  
15     {  
16         for (int y = 0; y < (this.YLength - 1); y++)  
17         {  
18             string line = this.sr.ReadLine();  
19             for (int x = 0; x < (this.XLength - 1); x++)  
20             {  
21                 map[x, y] = line[x];  
22             }  
23         }  
24     }  
25 }  
26   
27 public void DrawContent(SpriteBatch spriteBatch)  
28 {  
29     for(int y = 0; y < this.YLength; y++)  
30     {  
31         for (int x = 0; x < this.XLength; x++)  
32         {  
33             switch (this.map[x,y])  
34             {  
35                 case '1': tile.DrawTile(spriteBatch, x, y, 1); break;  
36                 case '2': tile.DrawTile(spriteBatch, x, y, 2); break;  
37             }  
38         }  
39     }  
40 }  

When I use this, I get "Index was outside the bounds of the array." on line 21,
map[x, y] = line[x]; 

Thanks.

Comments

Feel free to leave a comment...
and oh, if you want a pic to show with your comment, go get a gravatar!