NullReferenceExeption when reading from a file

Posted by Whitey on Stack Overflow See other posts from Stack Overflow or by Whitey
Published on 2010-05-08T23:28:26Z Indexed on 2010/05/08 23:38 UTC
Read the original article Hit count: 221

Filed under:
|
|
|
|

I need to read a file structured like this:

01000
00030
00500
03000
00020

And put it in an array like this:

int[,] iMap = new int[iMapHeight, iMapWidth] {
{0, 1, 0, 0, 0},
{0, 0, 0, 3, 0},
{0, 0, 5, 0, 0},
{0, 3, 0, 0, 0},
{0, 0, 0, 2, 0},
};

Hopefully you see what I'm trying to do here. I was confused how to do this so I asked here on SO, but the code I got from it gets this error:

Object reference not set to an instance of an object.

I'm pretty new to this so I have no idea how to fix it... I only barely know the code:

protected void ReadMap(string mapPath)
{
    using (var reader = new StreamReader(mapPath))
    {
        for (int i = 0; i < iMapHeight; i++)
        {
            string line = reader.ReadLine();
            for (int j = 0; j < iMapWidth; j++)
            {
                iMap[i, j] = (int)(line[j] - '0');
            }
        }
    }
}

The line I get the error on is this:

iMap[i, j] = (int)(line[j] - '0');

Can anyone provide a solution? Thank you. :)

© Stack Overflow or respective owner

Related posts about c#

Related posts about readfile