如何从文件中向列表框添加指定的项目?

时间:2017-09-06 11:43:25

标签: c#

我们说我有一些文本文件,我想在列表框中从一行到另一行加载行,省略该文件中的第一行和最后一行。可以吗?

enter image description here

private void metroButton18_Click(object sender, EventArgs e)
    {
        OpenFileDialog f = new OpenFileDialog();
        if (f.ShowDialog() == DialogResult.OK)
        {
            listBox3.Items.Clear();

            List<string> lines = new List<string>();
            using (StreamReader sr = new StreamReader(f.OpenFile()))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    listBox3.Items.Add(line);
                }
            }
        }
    }

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

使用File.ReadAllLines Method并跳过循环中的第一个和最后一个索引:

var path = @"C:\temp\MyTest.txt";
var allLines = File.ReadAllLines(path);

for(var i = 1; i < allLines.Length - 1; i++)
{
    listBox3.Items.Add(allLines[i]);
}

使用 OpenFileDialog 打开文件:

OpenFileDialog f = new OpenFileDialog();
if (f.ShowDialog() == DialogResult.OK)
{
    listBox3.Items.Clear();

    var allLines = File.ReadAllLines(f.FileName);
    for(var i = 1; i < allLines.Length - 1; i++)
    {
        listBox3.Items.Add(allLines[i]);
    }
}

答案 1 :(得分:1)

读取循环外的第一行:

line = sr.ReadLine();
while ((line = sr.ReadLine()) != null)
{
    listBox3.Items.Add(line);
}

完成从文件中读取后,只需删除最后一项:

listBox3.Items.RemoveAt(listBox3.Items.Count);

答案 2 :(得分:1)

这个怎么样?

OpenFileDialog f = new OpenFileDialog();
if (f.ShowDialog() == DialogResult.OK) {
    listBox1.Items.Clear();
    List<string> lines = new List<string>();
    using (StreamReader sr = new StreamReader(f.OpenFile())) {
          string line;
          while ((line = sr.ReadLine()) != null) {
                lines.Add(line); // add lines to list first
          }
    }
    string[] resultArray = lines.Skip(1).Reverse().Skip(1).Reverse().ToArray();
//skip first one , reverse so last one is the first now, skip again and reverse again to get actual list
    listBox1.Items.AddRange(resultArray);
}

希望有所帮助,