简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM