Reputation: 45
I've had the error when I was still using double.parse or int.parse in place of ConvertToDouble
and ConvertToInt32
, respectively.
Here's the code:
ArrayList Webpages = new ArrayList();
String FileName = "Medium.txt";
StreamReader newSR = new StreamReader(FileName);
while (!newSR.EndOfStream)
{
string[] data = (newSR.ReadLine()).Split(',');
Webpage newEntry = new Webpage();
newEntry.size = Convert.ToDouble(data[0]);
newEntry.visitCount = Convert.ToInt32(data[1]);
newEntry.name = data[2];
Webpages.Add(newEntry);
}
And the Textfile:
5.26,46,WebPage1
7.44,76,WebPage2
8.35,42,WebPage3
46.2,9,WebPage4
12.44,124,WebPage5
10.88,99,WebPage6
10.66,984,WebPage7
This is my error message:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.
I'm getting the error message by the line that reads: newEntry.size = Convert.ToDouble(data[0])
Upvotes: 1
Views: 1496
Reputation: 2009
Computer culture effect your delimeter types. In this case if delimeter is .
you can add InvariantCulture options.
newEntry.size = Convert.ToDouble(data[0], CultureInfo.InvariantCulture);
Also end of file may leads error if there is empty line. This way can be more secure.
while (!newSR.EndOfStream)
{
string line = newSR.ReadLine();
if(string.IsNullOrEmpty(line)
break;
string[] data = (line).Split(',');
............
Upvotes: 3