开发者

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

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开发者_StackOverflow社区:

richTextBox5.Text = File.ReadAllText("ignore.txt");


String text = File.ReadAllText("ignore.txt");

var result = Regex.Split(text, "\r\n|\r|\n");

foreach(string s in result)
{
  lstBox.Items.Add(s);
}


string[] lines = System.IO.File.ReadAllLines(@"ignore.txt");

foreach (string line in lines)
{
    listBox.Items.Add(line);
}


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜