I am having trouble with streamreader in c# - c#

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();
}
}

var lines = File.ReadAllLines( fileName );
foreach (var l in lines )
{
listBox1.Items.Add( l );
}
assuming that you have
email1#email1.com
email2#email2.com
in your file (this is what I understood from your description).

use this:
string line;
while((line = reader.ReadLine()) != null)
listBox1.Items.Add(line);

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.

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...

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

Related

C# loading listView subItems from file using StreamReader

I need some help with loading text file into a listView. Text file looks like this:
1,6 sec,5 sec,1 sec,17,
2,6 sec,4 sec,2 sec,33,
3,7 sec,5 sec,3 sec,44,
I have to load this into a listView control and every subitem should be separated by comma (or any other character). I tried something like this:
using (var sr = new StreamReader(file))
{
string fileLine = sr.ReadLine();
foreach (string piece in fileLine.Split(','))
{
listView1.Items.Add(piece);
}
sr.Close();
}
it would work just fine apart from only first line is loaded to the first column in listview. I cannot figure it out.
Thanks for your time!
KR!
You have to advance to the next line, you can use a while-loop:
using (var sr = new StreamReader(file))
{
string fileLine;
while ((fileLine = sr.ReadLine()) != null)
{
foreach (string piece in fileLine.Split(','))
{
listView1.Items.Add(piece);
}
}
}
Note that you don't need to close the stream manually, that is done by the using-statement.
Another way is using File.ReadLines or File.ReadAllLines which can help to simplify your code:
var allPieces = File.ReadLines(file).SelectMany(line => line.Split(','));
foreach(string piece in allPieces)
listView1.Items.Add(piece);
using (var sr = new StreamReader(file))
{
while(!sr.EndOfStream)
{
string fileLine = sr.ReadLine();
foreach (string piece in fileLine.Split(','))
{
listView1.Items.Add(piece);
}
sr.Close();
}
}
Ι guess you just have to add:
while (!sr.EndOfStream)
{
string fileLine = sr.ReadLine();
foreach (string piece in fileLine.Split(','))
{
listView1.Items.Add(piece);
}
}
sr.Close();// close put the end of while scope beacause you have a multiline text this code can't be read second line, and throw exceptions this code.

Putting textfile into Listbox using streamreader

I was wondering how i can make the program read a text file and put the contents in the listbox using 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());
}
Using File.ReadAllLines
Be aware of the # at the beginning of the file path. Using backslash in a string literal must be escaped if # 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);
}
}
An much easier way is to use File.ReadAllLines
string[] lines = File.ReadAllLines("yourFile");
foreach(string line in lines)
{
ListBox1.Items.Add(line);
}
using File.ReadAllLines also,
string[] lines = File.ReadAllLines( #"yourFile" );
lines.ForEach( x => Listbox1.Items.Add( x ) );

Remove Stop Words From text File

i want to remove stop words from my text file and i write the following code for this purpose
TextWriter tw = new StreamWriter("D:\\output.txt");
private void button1_Click(object sender, EventArgs e)
{
StreamReader reader = new StreamReader("D:\\input1.txt");
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(' ');
string[] stopWord = new string[] { "is", "are", "am","could","will" };
foreach (string word in stopWord)
{
line = line.Replace(word, "");
tw.Write("+"+line);
}
tw.Write("\r\n");
}
but it doesn't show the result in the output file and the output file remain empty.
A regular expression might be perfect for the job:
Regex replacer = new Regex("\b(?:is|are|am|could|will)\b");
using (TextWriter writer = new StreamWriter("C:\\output.txt"))
{
using (StreamReader reader = new StreamReader("C:\\input.txt"))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
replacer.Replace(line, "");
writer.WriteLine(line);
}
}
writer.Flush();
}
This method will only replace the words with blanks and do nothing with the stopwords if they are part of another word.
Good luck with your quest.
The following works as expected for me. However, it's not a good approach because it will remove the stop words even when they are part of a larger word. Also, it doesn't clean up extra spaces between removed words.
string[] stopWord = new string[] { "is", "are", "am","could","will" };
TextWriter writer = new StreamWriter("C:\\output.txt");
StreamReader reader = new StreamReader("C:\\input.txt");
string line;
while ((line = reader.ReadLine()) != null)
{
foreach (string word in stopWord)
{
line = line.Replace(word, "");
}
writer.WriteLine(line);
}
reader.Close();
writer.Close();
Also, I recommend using using statements for when you create your streams in order to ensure the files are closed in a timely manner.
You should wrap your IO objects in using statements so that they are disposed properly.
using (TextWriter tw = new TextWrite("D:\\output.txt"))
{
using (StreamReader reader = new StreamReader("D:\\input1.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(' ');
string[] stopWord = new string[] { "is", "are", "am","could","will" };
foreach (string word in stopWord)
{
line = line.Replace(word, "");
tw.Write("+"+line);
}
}
}
}
Try wrapping StreamWriter and StreamReader in using() {} clauses.
using (TextWriter tw = new StreamWriter(#"D:\output.txt")
{
...
}
You may also want to call tw.Flush() at the very end.

Changing a part of text line in a file on mouse doubleclick by comparing it with a value

I have a file-message.txt that contains raw data, my application reads the file, parses it and displays the data accordingly in the listview. The raw data contains a word called REC UNREAD meaning the record is unread. So for the first time when message is read it is UNREAD and I display such messages in bold. After I read it(Using doubleclick event) the word REC UNREAD should be changed to REC READ. This is what I have I tried, not working though
private void lvwMessages_MouseDoubleClick_1(object sender, MouseEventArgs e)
{
try
{
ListViewItem item = lvwMessages.SelectedItems[0];
if(item.Font.Bold)
{
lvwMessages.SelectedItems[0].Font = new Font(lvwMessages.Font, FontStyle.Regular);
string tfile = File.ReadAllText("C:\\message.txt");
string m1 = lvwMessages.SelectedItems[0].SubItems[1].Text;
string m2 = lvwMessages.SelectedItems[0].SubItems[2].Text;
//No idea how to go forward from here
This is a sample line in my text file:
+CMGL: 2,"REC UNREAD","+919030665834","","2012/08/10 17:04:15+22"
sample message
In simple words I should be able to search for the line containing m1 and m2(as in the code) and replace the REC UNREAD with REC READ.
This should solve your problem--
ListViewItem item = lvwMessages.SelectedItems[0];
if(item.Font.Bold)
{
lvwMessages.SelectedItems[0].Font = new Font(lvwMessages.Font, FontStyle.Regular);
string tfile = File.ReadAllText("C:\\message.txt");
string m1 = lvwMessages.SelectedItems[0].SubItems[1].Text;
string m2 = lvwMessages.SelectedItems[0].SubItems[2].Text;
string line = string.Empty;
string nfile= "";
using (StreamReader sr = new StreamReader("C:\\message.txt"))
{
while ((line = sr.ReadLine()) != null)
{
if (line.Contains(m2))
{
string pline = line;
string result = line.Replace("REC UNREAD", "REC READ");
nfile= tfile.Replace(pline, result);
}
}
sr.Close();
}
StreamWriter sw = new StreamWriter("C:\\message.txt");
{
sw.Write(nfile);
}
sw.Close();
}
you can try with this code based on IndexOf and Replace
string line = string.Empty;
using (StreamReader sr = new StreamReader("C:\\message.txt"))
{
while ((line = sr.ReadLine()) != null)
{
if (line.IndexOf(m1) > 0 &&
line.IndexOf(m2) )
{
var result = line.Replace(m2, "READ");
}
}
}

How to add lines of a text file into individual items on a ListBox (C#)

How would it be possible to read a text file with several lines, and then to put each line in the text file on a separate row in a ListBox?
The code I have so far:
richTextBox5.Text = File.ReadAllText("ignore.txt");
String text = File.ReadAllText("ignore.txt");
var result = Regex.Split(text, "\r\n|\r|\n");
foreach(string s in result)
{
lstBox.Items.Add(s);
}
string[] lines = System.IO.File.ReadAllLines(#"ignore.txt");
foreach (string line in lines)
{
listBox.Items.Add(line);
}
Write a helper method that return the collection of lines
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;
}
}
}
use it
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()
You should use a streamreader to read the file one line at a time.
using (StreamReader sr = new StreamReader("ignore.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
listBox1.Items.Add(line);
}
StreamReader info -> http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx
ListBox info -> http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.aspx

Categories