Search code examples
c#textarrayliststreamreader

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);
            }
        }

Solution

  • 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.