如何读取包含多行的文本文件,然后将文本文件中的每一行放在ListBox中的单独行上?
到目前为止我的代码:
richTextBox5.Text = File.ReadAllText("ignore.txt");
答案 0 :(得分:3)
String text = File.ReadAllText("ignore.txt");
var result = Regex.Split(text, "\r\n|\r|\n");
foreach(string s in result)
{
lstBox.Items.Add(s);
}
答案 1 :(得分:3)
string[] lines = System.IO.File.ReadAllLines(@"ignore.txt");
foreach (string line in lines)
{
listBox.Items.Add(line);
}
答案 2 :(得分:0)
您应该使用streamreader一次读取一行文件。
using (StreamReader sr = new StreamReader("ignore.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
listBox1.Items.Add(line);
}
StreamReader信息 - > http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx
列表框信息 - > http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.aspx
答案 3 :(得分:0)
编写一个返回行集合的辅助方法
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;
}
}
}
使用它
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()