Reputation: 1
I am having a little trouble with the streamreader.
I am opening emails from the file dialog, and those emails are placed inside a listbox. each letter in the emails, are on one line, as shown in the picture below.
I want the emails to be on one line, can some one help me, this is giving me a headache.
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();
}
}
Upvotes: 0
Views: 86
Reputation: 33476
using (StreamReader sr = new StreamReader(File.OpenRead(fileName)))
{
while (sr.Peek() >= 0)
{
listBox1.Items.Add(sr.ReadLine());
}
}
Reference: http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline
Upvotes: 0
Reputation: 10376
string containl chars, so foreach (var l ...)
iterates through chars in line.
You should replace your foreach with
foreach( var email in line.Split(' '))
In case your emails separated with spaces. Another approach would be File.ReadAllLines, in case emails in your file is on separate lines...
Upvotes: 0
Reputation: 8818
Use it as follow:
using (StreamReader sr = new StreamReader(File.OpenRead(fileName))) { string line; while ((line = sr.ReadLine()) != null) { listBox1.Items.Add(line.ToString()); } }
This reads all the lines in the file and adds it to the listbox line by line.
Upvotes: 0
Reputation: 174289
use this:
string line;
while((line = reader.ReadLine()) != null)
listBox1.Items.Add(line);
Upvotes: 1
Reputation: 48230
var lines = File.ReadAllLines( fileName );
foreach (var l in lines )
{
listBox1.Items.Add( l );
}
assuming that you have
[email protected]
[email protected]
in your file (this is what I understood from your description).
Upvotes: 1