Bramble
Bramble

Reputation: 1395

C# file input from text file

I have a function like this:

   List<float> myList = new List(float);

     public void numbers(string filename)
    {
        string input;
        float number;

        if (System.IO.File.Exists(filename) == true)
        {
            System.IO.StreamReader objectReader;
            objectReader = new System.IO.StreamReader(filename);

            while ((input = objectReader.ReadLine()) != null)
            {
                number = Convert.ToSingle(input);
                myList.Add(number);
            }
            objectReader.Close();
        }
        else
        {
            MessageBox.Show("No Such File" + filename);
        }
    }

Where Im trying to add numbers (floats) from a text file into a List. But I keep getting errors saying wrong format. The numbers in the text file are one number per line...any help?

Upvotes: 0

Views: 5150

Answers (6)

SergeyKazachenko
SergeyKazachenko

Reputation: 66

By the way, if (System.IO.File.Exists(filename) == true) can be shortened to if (System.IO.File.Exists(filename))

Upvotes: 0

Andrew
Andrew

Reputation: 139

There's a wonderful free package called FileHelpers which helps with importing data from all sorts of text files. The advantage with this is that a lot of the deeper error handling is already in place.

Upvotes: 0

David Hall
David Hall

Reputation: 33183

Your code worked fine for me except for the case of a newline (and of course for entries that were not numbers at all)

Here is a version that should work for you, using a tryParse to check if each line can convert to a single):

    public void Numbers(string filename)
    {
        List<float> myList = new List<float>();     

        string input;

        if (System.IO.File.Exists(filename) == true)
        {
            System.IO.StreamReader objectReader;
            objectReader = new System.IO.StreamReader(filename);
            while ((input = objectReader.ReadLine()) != null)
            {
                Single output;
                if (Single.TryParse(input, out output ))
                {
                    myList.Add(output);
                }
                else
                {
                   // Huh? Should this happen, maybe some logging can go here to track down why you couldn't just use the .Convert()
                }
            }
            objectReader.Close();

        }
        else
        {
            MessageBox.Show("No Such File" + filename);
        }
    }

As Mike C rightly points out, this could be potentially risky - swallowing good data that has been corrupted by the output process. The tryParse method returns false when it fails so you could add in an else branch and some logging to check just what is causing the failures and see if there is another bug floating around that can be corrected.

Upvotes: 3

bashmohandes
bashmohandes

Reputation: 2376

I would suggest you do a Trim call like this

number = Convert.ToSingle(input.Trim());

However, a better code would be using a TryParse call

float tmp;
if(float.TryParse(input.Trim(), out tmp)
{
   mylist.Add(tmp);
}

Upvotes: 4

Mike Cole
Mike Cole

Reputation: 14743

Are there spaces or commas or anything? The best thing to do would be to set a breakpoint on

number = Convert.ToSingle(input);

to see what input is actually before you try to convert it.

Upvotes: 0

GrayWizardx
GrayWizardx

Reputation: 21231

Do you have any blank lines in the file, or failures to convert the number? My guess is that you have a line which is not castable to float from its current format. You should make sure you sanitize the lines before reading them in (strip off everything that is not a number using a regex) and throw the line out if it fails the check.

One thing you might do is use double instead and do a Convert.ToDouble().

Upvotes: 0

Related Questions