Search code examples
parsingexceptionformatintstreamreader

c# Format exception was unhandled


I have a method that fills up the elements of an int[,]. The elements that need to be filled are stored in a .txt file like this:

 1
 1
 2
 2

Meaning that I have to fill up the [1,1] and [2,2] element.

For this I use this but it gives the error above

int x = 0;
int y = 0;
for (int i = 0; i < 2; i++)
{
    x = int.Parse(SR.ReadLine());
    y = int.Parse(SR.ReadLine());
    mezo.mezo[x, y] = 1;
}

Thanks in advance!


Solution

  • According to MSDN(http://msdn.microsoft.com/en-IN/library/b3h1hf19.aspx) a FormatException is thrown when:

    s is not in the correct format.

    s in your case is SR.ReadLine() which is returning some value that is not recognized as a number format.

    At first look it might be because of whitespaces in your file.

    Try

    SR.ReadLine().Trim()

    OR

    NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite for the number style in the Parse method.