Your error is from these lines:
Console.WriteLine(rea.ReadLine());
ad.Add(Int32.Parse(rea.ReadLine()));
What’s happening is you are getting the count of the number of lines in the file. Say your file has 10 lines. When the loop reaches the last line and you call ReadLine
method in Console.WriteLine(rea.ReadLine());
, it returns the last line. But then you call Readline
method again in ad.Add(Int32.Parse(rea.ReadLine()));
and the it returns null because the end of file (EOF) has been reached and Int32.Parse
throws exception because it cannot convert a null into a number.
This is from MSDN about ReadLine
method:
The next line from the input stream, or null if the end of the input stream is reached.
So not only are you getting the exception, but your sum will be off too because your ad
list will contain only half the numbers in your file. So if your file has 10 lines, it will only have 5 numbers.
Fix
If your file has numbers and you are sure they are numbers, you can use Int32.Parse
. If you are unsure, then use Int32.TryParse
which will try and if it fails it will return false. If all you need is the sum and nothing else, you can do it in one line of code like this:
File.ReadLines("PathOfYourFile").Sum(line => int.Parse(line));
If you are unsure and the file may contain non numeric data, then do it like this:
File.ReadLines("PathOfYourFile").Sum(line =>
{
int possibleNumber;
if (int.TryParse(line, out possibleNumber)
{
// success so return the number
return possibleNumber;
}
else
{
// Maybe log the line number or throw the exception to
// stop processing the file or
// return a zero and continue processing the file
return 0;
}
}
Finally if you want to do it your way, remove this line and if your file only has numbers, then all should be fine:
// remove this so you do not read the line
Console.WriteLine(rea.ReadLine());
1
solved Not able to get sum of array in C#