StreamReader row and line delimiters - c#

I am trying to figure out how to tokenize a StreamReader of a text file. I have been able to separate the lines, but now I am trying to figure out how to break down those lines by a tab delimiter as well. This is what I have so far.
string readContents;
using (StreamReader streamReader = new StreamReader(#"File.txt"))
{
readContents = streamReader.ReadToEnd();
string[] lines = readContents.Split('\r');
foreach (string s in lines)
{
Console.WriteLine(s);
}
}
Console.ReadLine();

string readContents;
using (StreamReader streamReader = new StreamReader(#"File.txt"))
{
readContents = streamReader.ReadToEnd();
string[] lines = readContents.Split('\r');
foreach (string s in lines)
{
string[] lines2 = s.Split('\t');
foreach (string s2 in lines2)
{
Console.WriteLine(s2);
}
}
}
Console.ReadLine();
not really sure if that is what you want, but... it breaks (tab) the already broken (return) lines

Just call Split() on each of the lines and keep them in a List. If you need an array you can always call ToArray() on the list:
string readContents;
using (StreamReader streamReader = new StreamReader(#"File.txt"))
{
readContents = streamReader.ReadToEnd();
string[] lines = readContents.Split('\r');
List<string> pieces = new List<string>();
foreach (string s in lines)
{
pieces.AddRange(s.Split('\t'));
Console.WriteLine(s);
}
}
Console.ReadLine();

Related

CSV StreamReader deletes blanks (semicolon)

When I read a CSV (smicolon separated) with this method:
public List<string> LoadCSV()
{
List<string> displayName = new List<string>();
List<string> groupName = new List<string>();
using (StreamReader reader = new StreamReader(#"\\aPath\to\aFile.csv"))
{
while (!reader.EndOfStream)
{
String line = reader.ReadLine();
String[] values = line.Split(';');
displayName.Add(values[0]);
groupName.Add(values[6]);
}
}
return displayName;
}
The blanks in displayName get deleted.
One line in the file:
Adobe Acrobat Standard - (Win XP);16477;2;3657;AD Group;1233xxoo_AcrobatStd;1835
For my understanding, this should give for the line above this result:
Adobe Acrobat Standard - (Win XP)
But it's this:
AdobeAcrobatStandard-(WinXP)
Can somebody help?
It's an OutlookAddin. This is how I run the method:
string bodyText = "RealNames:\n";
foreach (string s in LoadCSV()) {
bodyText += s +"\n";
}
openMail.Body = bodyText;

How do I show my data via a loop outside of a StreamReader

So I am trying display my data from a StreamReader outside of the using portion. I am able to display it all INSIDE of the StreamReader however showing it OUTSIDE of the StreamReader is proving more complicated.
I understand that my while loop inside the StreamReader will show all the data I need (and it is). But I need it to show from the for loop that I have at the bottom. (While loop was left in just as a reference).
When I run it through the for loop I either get
"end
end
end
end"
or
"end
of
record
indicator"
I get the "Ends" when i use the array index number in the for loop, and the "end of record indicator" when i use the "i".
How can I get it to display what my while loop is displaying?
class Program
{
static void Main(string[] args)
{
string[] lineOutVar;
using (StreamReader readerOne = new StreamReader("../../FileIOExtraFiles/DataFieldsLayout.txt"))
{
string lineReader = readerOne.ReadLine();
string[] lineOutput = lineReader.Split('\n');
lineOutVar = lineOutput;
while (readerOne.EndOfStream == false)
{
lineOutVar = readerOne.ReadLine().Split();
Console.WriteLine(lineOutVar[0]);
}
}
for (int i = 0; i < lineOutVar.Length; i++)
{
Console.WriteLine(lineOutVar[0]);
}
Use List class.
List<string> lineOutVar = new List<string>();
using (System.IO.StreamReader readerOne = new System.IO.StreamReader("../../FileIOExtraFiles/DataFieldsLayout.txt"))
{
while(readerOne.EndOfStream == false)
{
string lineReader = readerOne.ReadLine();
lineOutVar.Add(lineReader); //add the line to the list of string
}
}
foreach(string line in lineOutVar) //loop through each of the line in the list of string
{
Console.WriteLine(line);
}
to get the content:
string[] lineOutVar;
List<string[]> lst_lineOutVar = new List<string[]>();
using (StreamReader readerOne = new StreamReader("E:\\TEST\\sample.txt"))
{
string lineReader = readerOne.ReadLine();
string[] lineOutput = lineReader.Split('\n');
lineOutVar = lineOutput;
while (readerOne.EndOfStream == false)
{
lineOutVar = new string[1];
lineOutVar = readerOne.ReadLine().Split();
lst_lineOutVar.Add(lineOutVar);
//Console.WriteLine(lineOutVar[0]);
}
String getcontent = string.Empty;
foreach (var getLst in lst_lineOutVar)
{
getcontent = getcontent + "," + getLst[0].ToString();
}
Console.WriteLine(getcontent);
}
You could also just skip the StreamReader and use File.ReadAllLines:
string[] lineOutVar = File.ReadAllLines("../../FileIOExtraFiles/DataFieldsLayout.txt");
Now you have an array of the file lines, and you can loop over them and split them however you like.

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.

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.

I am having trouble with streamreader in 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

Categories