How to add lines of a text file into individual items on a ListBox (C#)

前端 未结 4 1892
渐次进展
渐次进展 2021-01-23 00:52

How would it be possible to read a text file with several lines, and then to put each line in the text file on a separate row in a ListBox?

The code I have so far:

4条回答
  •  抹茶落季
    2021-01-23 01:02

    Write a helper method that return the collection of lines

       static IEnumerable ReadFromFile(string file) 
        {// check if file exist, null or empty string
            string line;
            using(var reader = File.OpenText(file)) 
            {
                while((line = reader.ReadLine()) != null) 
                {
                    yield return line;
                }
            }
        }
    

    use it

    var lines = ReadFromFile(myfile);
    myListBox.ItemsSource = lines.ToList(); // or change it to ObservableCollection. also you can add to the end line by line with myListBox.Items.Add()
    

提交回复
热议问题