I have some problems with StreamReader. Firstly, below, is my simple code:
using (StreamReader reader = new StreamReader("Content/Levels/" + mapName + ".txt"))
{
for (int i = 0; i < 20; i++)
for (int j = 0; j < 36; j++)
{
string[] objLoc = reader.ReadLine().Split(',');
map[i, j] = Convert.ToInt32(objLoc[j]);
}
}
So, I have a text file which has rows and columns, just like an array. Each position holds an integer. Those integers are delimited by , chars.
I want to read each character from the position within the text file, and then convert it to an actual integer and add it to a separate array. I’ll read from that array to build the map after the code I’ve shown you.
Being new to C# and programming, I assume that my code actually reads every position from a line using that Split method, and then I use the read char to insert it in the map array.
Am I doing it right? At the moment, I’m getting an exception:
NullReferenceException was unhandled: Object reference not set to an instance of an object.
I’ve read the documentation from MS also. Stumbled upon numerous similar problems, but none fixed my issue.
Any help would be highly appreciated!
You are reading a whole new line in your inner loop, which means you run out of lines fast. You need to read a new line in the outer loop, and loop throught the result of the split (the inidividual elements) in the inner loop
Try something like
Note: you will need to check for errors in case the line does not contain enough elements or the file is too short. The conversion to
intmight fail as well