【问题标题】:How to read from a text file and store to array list in c#?如何从文本文件中读取并存储到 C# 中的数组列表?
【发布时间】:2015-11-15 02:13:06
【问题描述】:

我正在尝试读取文本文件并将其数据存储到数组列表中。它的工作没有任何错误。我的文本文件里面是这样的。

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

【问题讨论】:

  • 您是否使用调试器完成了循环?
  • 你的变量 FileName 已经是一个字符串,所以你不需要调用 ToString()。局部变量也应该以小写字母开头。
  • @shona92 您的代码是正确的,但您的文本文件格式值得怀疑。您需要按照输入中显示的方式设置每一行。
  • 旁注:将System.IO.StreamReader放入使用,即using(System.IO.StreamReader file = new System.IO.StreamReader(FileName.ToString())) {...}
  • @X-TECH 文本文件格式为 .txt,每个数字都从新行开始。

标签: c# text arraylist streamreader


【解决方案1】:

我认为您的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);
    }
}

其他方面,这里似乎一切都很好。

【讨论】:

  • 问题已解决。有效。非常感谢您的支持。
【解决方案2】:

尝试使用 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));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-26
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多