shona92
shona92

Reputation: 63

How to read from a text file and store to array list in c#?

I'm trying to read a text file and store it's data to an array list. It's working without any errors. Inside of my text file is like this.

277.18
311.13
349.23
277.18
311.13
349.23
277.18
311.13
349.23 

but in console output I can see this much of data.

277.18
311.13
349.23
349.23
**329.63
329.63
293.66
293.66
261.63
293.66
329.63
349.23
392**
277.18
311.13
349.23
277.18
311.13
349.23
277.18
311.13
349.23

Also Bolded numbers are not in my text file. Here is my code. how to solve this?? can Someone help me.. please...

        OpenFileDialog txtopen = new OpenFileDialog();
        if (txtopen.ShowDialog() == DialogResult.OK)
        {
            string FileName = txtopen.FileName;
            string line;
            System.IO.StreamReader file = new System.IO.StreamReader(FileName.ToString());
            while ((line = file.ReadLine()) != null)
            {
                list.Add(double.Parse(line));
            }
            //To print the arraylist
            foreach (double s in list)
            {
                Console.WriteLine(s);
            }
        }

Upvotes: 4

Views: 1694

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

Try using Linq which doesn't add anything to existing list:

if (txtopen.ShowDialog() == DialogResult.OK) {
  var result = File
    .ReadLines(txtopen.FileName)
    .Select(item => Double.Parse(item, CultureInfo.InvariantCulture));

  // if you need List<Double> from read values:
  //   List<Double> data = result.ToList();
  // To append existing list:
  //   list.AddRange(result);

  Console.Write(String.Join(Environment.NewLine, result));
}

Upvotes: 1

Shaharyar
Shaharyar

Reputation: 12459

I think your list already contains some of the data, you should clear it before adding new file data to it.

OpenFileDialog txtopen = new OpenFileDialog();
if (txtopen.ShowDialog() == DialogResult.OK)
{
    list.Clear();   // <-- clear here

    string FileName = txtopen.FileName;
    string line;
    System.IO.StreamReader file = new System.IO.StreamReader(FileName.ToString());
    while ((line = file.ReadLine()) != null)
    {
        list.Add(double.Parse(line));
    }
    //To print the arraylist
    foreach (double s in list)
    {
        Console.WriteLine(s);
    }
}

Other wise every thing seems to be fine here.

Upvotes: 2

Related Questions