1

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])

2
  • 1
    Have you debugged to check what the value of data[0] is when it fails? (I'm wondering whether you're reading a blank line at the end of the file.) Is it possible that you're in a culture where the decimal separate is , rather than .? Commented Apr 7, 2018 at 9:52
  • tried your code, its working except I didnt used your Webpage newentry object, what is it ?? Commented Apr 7, 2018 at 10:03

1 Answer 1

3

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(',');
     ............
Sign up to request clarification or add additional context in comments.

1 Comment

neither double.Parse nor Convert.ToDouble throw a System.FormatException if the delimiter is , or .. They simply parse the value wrong. So culture dependent delimiter cannot be the problem here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.