Loading text file into listbox

2019-01-28 12:20发布

问题:

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.

回答1:

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


回答2:

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

            }
        }
    }


回答3:

Try something like this:

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


回答4:

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

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.