I have been unable to apply any solutions to this issue. The exception happens to this line here: currentMap[row, col] = Int32.Parse(s); What I am wanting to do is pass this method a specific file storing rows of numbers like this:
1,1,1
1,0,1
1,1,1
I then want each number to be stored in int[,] currentMap which gets returned. The file I am using contains no large numbers. I think that the size of array I am creating is right and so I don't understand why this isn't working. I am used to doing similar stuff using NextInt in java but I couldn't find any alternative for c#.
Thanks for any help.
private int[,] LoadMapArray(String filename)
{
int[,] currentMap;
int rows = 0;
int cols = 0;
StreamReader sizeReader = new StreamReader(filename);
using (var reader = File.OpenText(filename))
{
while (reader.ReadLine() != null)
{
string line = sizeReader.ReadLine();
cols = line.Length;
rows++;
}
}
currentMap = new int[rows,cols];
StreamReader sr = new StreamReader(filename);
for (int row = 0; row < rows + 1; row++)
{
string line = sr.ReadLine();
string[] split = new string[] {","};
string[] result;
result = line.Split(split, StringSplitOptions.None);
int col = 0;
foreach (string s in result)
{
currentMap[row, col] = Int32.Parse(s);
col++;
}
}
return currentMap;
}
Edit: Code was fixed after changing how I was accessing the file. I then had to change this to catch null:
for (int row = 0; row < rows + 1; row++)
{
string line = sr.ReadLine();
string[] split = new string[] { "," };
string[] result;
if (line != null)
{
result = line.Split(split, StringSplitOptions.None);
int col = 0;
foreach (string s in result)
{
currentMap[row, col] = Int32.Parse(s);
col++;
}
}
}