使用streamreader将文本文件放入List Box

时间:2014-03-06 11:03:28

标签: c# streamreader

我想知道如何让程序读取文本文件并使用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());
    }

3 个答案:

答案 0 :(得分:1)

使用File.ReadAllLines

请注意文件路径开头的@。如果@ not used,则必须转义字符串文字中的反斜杠。

ListBox1.Items.AddRange(File.ReadAllLines(@"C:\Users\tommy\Desktop\WindowsFormsApplication9\WindowsFormsApplication9\bin\Debug\transactions.txt"));

Using StreamReader

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

还使用File.ReadAllLines

string[] lines = File.ReadAllLines( @"yourFile" );

lines.ForEach( x => Listbox1.Items.Add( x ) );