如何在c#中从文本文件读取并存储到数组列表?

4

我正在尝试读取一个文本文件,并将其数据存储到一个数组列表中。目前没有任何错误发生。我的文本文件内部结构如下:

277.18
311.13
349.23
277.18
311.13
349.23
277.18
311.13
349.23 

但是在控制台输出中,我只能看到这么多的数据。

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

加粗的数字不在我的文本文件中。 这是我的代码。怎么解决??有人可以帮我吗..拜托了...

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

1
你用调试器检查过你的循环了吗? - Sebastian L
你的变量FileName已经是一个字符串,所以你不需要调用ToString()。此外,本地变量应该以小写字母开头。 - Vincent
@shona92,你的代码是正确的,但是你的文本文件格式有问题。你需要将每个设置为新行,就像你在输入中展示的那样。 - NASSER
注:将 System.IO.StreamReader 放入 using 中,即 using(System.IO.StreamReader file = new System.IO.StreamReader(FileName.ToString())) {...} - Dmitry Bychenko
@X-TECH的文本文件格式为 .txt,每个数字都是从新行开始。 - shona92
2个回答

2

我认为你的list已经包含了一些数据,你应该在添加新文件数据之前清空它。

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

除此之外,这里的一切都看起来很好。

问题已解决。它起作用了。非常感谢您的支持。 - shona92

1
尝试使用不会添加任何内容到现有列表的 Linq
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));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接