2012-08-17 65 views
0

我對streamreader有點麻煩。我在c中遇到了streamreader的問題#

我從文件對話框打開電子郵件,這些電子郵件放在列表框中。 電子郵件中的每個字母都在一行上,如下圖所示。

我希望電子郵件是在一條線上,有人能幫助我,這讓我很頭疼。

private void button2_Click(object sender, EventArgs e) 
{ 
    OpenFileDialog ofg = new OpenFileDialog(); 
    ofg.Filter = "Text Files|*.txt"; 
    if (ofg.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
    { 
     var fileName = ofg.FileName; 

     StreamReader sr = new StreamReader(File.OpenRead(fileName)); 
     var line = sr.ReadToEnd();   

     foreach (var l in line) 
      listBox1.Items.Add(l.ToString()); 

     sr.Dispose(); 
    } 
} 

example here

回答

1
 var lines = File.ReadAllLines(fileName); 

     foreach (var l in lines) 
     { 
      listBox1.Items.Add(l); 
     } 

假設你在你的文件中有

 [email protected] 
     [email protected] 

(這是我從你的描述可以理解)。

+0

感謝奏效 – 2012-08-17 10:10:05

1

使用本:

string line; 
while((line = reader.ReadLine()) != null) 
    listBox1.Items.Add(line); 
0

使用它作爲如下:

using (StreamReader sr = new StreamReader(File.OpenRead(fileName))) 
{ 
     string line; 

     while ((line = sr.ReadLine()) != null) 
     { 
      listBox1.Items.Add(line.ToString()); 
     } 
} 

這讀取文件中的所有行並將其添加到由線列表框線。

0

字符串包含字符,因此foreach (var l ...)在字符串中迭代。 你應該

foreach(var email in line.Split(' ')) 

取代你的foreach如果你用空格分隔的電子郵件。 另一種方法是File。 ReadAllLines,在你的文件的情況下的電子郵件是在單獨的行...