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

前端 未结 4 1888
渐次进展
渐次进展 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 00:56

    You should use a streamreader to read the file one line at a time.

    using (StreamReader sr = new StreamReader("ignore.txt"))
    {
      string line;
      while ((line = sr.ReadLine()) != null)
        listBox1.Items.Add(line);
    }
    

    StreamReader info -> http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx

    ListBox info -> http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.aspx

    0 讨论(0)
  • 2021-01-23 01:02

    Write a helper method that return the collection of lines

       static IEnumerable<string> 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()
    
    0 讨论(0)
  • 2021-01-23 01:17
    String text = File.ReadAllText("ignore.txt");
    
    var result = Regex.Split(text, "\r\n|\r|\n");
    
    foreach(string s in result)
    {
      lstBox.Items.Add(s);
    }
    
    0 讨论(0)
  • 2021-01-23 01:18
    string[] lines = System.IO.File.ReadAllLines(@"ignore.txt");
    
    foreach (string line in lines)
    {
        listBox.Items.Add(line);
    }
    
    0 讨论(0)
提交回复
热议问题