Reputation: 1329
A bit of a long title but I'll explain it here.
I have a text file named sample.txt
sample.txt
"105"|2015-01-01 00:00:00|"500"|John Smith"|"Facebook"|"Ohio"|"(555) 555-5555"
"110"|2016-05-20 01:40:00|"550"|David K"|"Twitter"|"Missouri"|"(555) 555-5555"
My goal is to read this file, seperate the words by the delimiter and spit out each of the fields on a new line. I have managed to do that but I cannot figure out how to make it move to the next line.
Currently it does what I want it to do, but only for the first line. I assumed line = sr.ReadLine()
would move to the next set but it doesn't.
String line;
try
{
StreamReader sr = new StreamReader("C:\\Users\\ME\\Documents\\sample.txt");
line = sr.ReadLine();
char delimiterChar = '|';
while (line != null)
{
string[] words = line.Split(delimiterChar);
foreach (string s in words)
{
Console.WriteLine(s);
line = sr.ReadLine();
}
}
sr.Close();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
Console.ReadKey();
}
finally
{
Console.WriteLine("Executing Finally Block");
Console.ReadKey();
}
Upvotes: 0
Views: 109
Reputation: 1396
You need to move line = sr.ReadLine();
out for the foreach
loop. Right now it is reading a new line for each string in the first line, which consumes the rest of the input.
It should be immediately after the foreach
loop, but still within the while
loop.
Upvotes: 2