C# 将文本文件加载到列表框中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9531375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:46:55  来源:igfitidea点击:

Loading text file into listbox

c#filetextlistbox

提问by Shannon Rothe

What I am wanting to achieve is loading a text file into a listbox. It seems simple enough but I need to recognise in the text file when there is a new line, and each new line needs to be a new item in the listbox.

我想要实现的是将文本文件加载到列表框中。这看起来很简单,但我需要在文本文件中识别新行,并且每个新行都需要是列表框中的一个新项目。

If this is possible, a reply would be much appreciated.

如果这是可能的,答复将不胜感激。

采纳答案by gaurawerma

This will work

这将工作

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

回答by Mithrandir

Try something like this:

尝试这样的事情:

listboxObject.DataSource = File.ReadAllLines("PathToYourFileHere");

回答by Michel Keijzers

You can read all text (file.ReadAllText or Alllines), I don't have a compiler here.

您可以阅读所有文本(file.ReadAllText 或 Alllines),我这里没有编译器。

Then add them to the list box, it is advised to trim the lines to get rid of whitespace at the beginning and end of each line.

然后将它们添加到列表框中,建议修剪行以去除每行开头和结尾的空格。

回答by Adumuah Dowuona

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

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

            }
        }
    }