pumuckl pumuckl - 2 months ago 12
C# Question

Why is this while loop omitting the first iteration?

I am new to coding and I've been racking my brain over this but really can't explain this to myself:

I have a csv file with a content like this:

line1_value1,line1_value2,line1_value3
line2_value1,line2_value2,line2_value3
line3 value1,line3_value2,line3_value3


For testing purposes I tried to print out the values with the following code:

static void Main(string[] args)
{

Program test = new Program();
test.printFile();


}

System.IO.StreamReader file = new System.IO.StreamReader(@"C:\some_file.csv");

public void printFile()
{
string line;

while ((line = file.ReadLine()) != null)
{

string[] substrings = file.ReadToEnd().Split(',');

foreach (var substring in substrings) {
Console.WriteLine(substring);

}

Console.ReadLine();
}

}


But it omits the first line and prints:

line2_value1
line2_value2
line2_value3
line3 value1
line3_value2
line3_value3


If I do it in a do while loop, it is working like intended:

public void printFile()
{
string line;

do
{
string[] substrings = file.ReadToEnd().Split(',');

foreach (var substring in substrings)
{
Console.WriteLine(substring);
}
}

while ((line = file.ReadLine()) != null);

Console.ReadLine();
}


This prints:

line1_value1
line1_value2
line1_value3
line2_value1
line2_value2
line2_value3
line3 value1
line3_value2
line3_value3


Why is the first line not showing up in the while loop?

Thanks in advance!

Answer

Let's see what you are doing:

while ((line = file.ReadLine()) != null)

So you read the first line from the file. Next, you do this:

string[] substrings = file.ReadToEnd().Split(',');

You read the remaining part of the file until the end. It does not go back to read the first line you have read and skipped. That's why it isn't working as expected.

I am not sure what the correct behavior should be since your reading doesn't seem to be line based (so why use ReadLine in the first place?). You could read yourself until the first , you encounter and process further based on that. Or read the entire file if it isn't too big as you are already doing in the second statement.

And further, the while loop is nonsense, since you read until the end of the file anyways. There will never be a second iteration!