我想知道如何让程序读取文本文件并使用streamreader将内容放入列表框中?
private void button1_Click(object sender, EventArgs e)
{
} (StreamReader stRead = new StreamReader("C:\Users\tommy\Desktop\WindowsFormsApplication9\WindowsFormsApplication9\bin\Debug\transactions.txt"))
{
while (!stRead.EndOfStream)
{
ListBox1.Items.Add(stRead.ReadLine());
}
答案 0 :(得分:1)
请注意文件路径开头的@。如果@ not used,则必须转义字符串文字中的反斜杠。
ListBox1.Items.AddRange(File.ReadAllLines(@"C:\Users\tommy\Desktop\WindowsFormsApplication9\WindowsFormsApplication9\bin\Debug\transactions.txt"));
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
ListBox1.Items.Add(line);
}
}
答案 1 :(得分:0)
更简单的方法是使用File.ReadAllLines
string[] lines = File.ReadAllLines("yourFile");
foreach(string line in lines)
{
ListBox1.Items.Add(line);
}
答案 2 :(得分:0)
string[] lines = File.ReadAllLines( @"yourFile" );
lines.ForEach( x => Listbox1.Items.Add( x ) );