more effective way of reading file with streamreader?

  • Thread starter Thread starter Jon Skeet [C# MVP]
  • Start date Start date
J

Jon Skeet [C# MVP]

VMI said:
I normally use the following sequence of code to read from a file. Is there
any other way I can do it where I don't have to do that first ReadLine()
that's outside of the loop? But if I don't do that, how am I going to
process that first line?

myReader.Open();
myVar = myReader.ReadLine(); //for first line of file
while (myVar != null)
{
/* do what I have to do with myVar */
myVar = myReader.ReadLine();
}

My normal code is something like:

string line;

while ( (line=myReader.ReadLine()) != null)
{
// Do something with line
}
 
I normally use the following sequence of code to read from a file. Is there
any other way I can do it where I don't have to do that first ReadLine()
that's outside of the loop? But if I don't do that, how am I going to
process that first line?

myReader.Open();
myVar = myReader.ReadLine(); //for first line of file
while (myVar != null)
{
/* do what I have to do with myVar */
myVar = myReader.ReadLine();
}

Thanks.
 
Hi,

You could try

myReader.Open();

while ( (myVar = myReader.ReadLine()) != null)
{
/* do what I have to do with myVar */
}

Or maybe:

myReader.Open();
do
{
/* do what I have to do with myVar */
myVar = myReader.ReadLine();
} while (myVar != null);


Martin
 
I didn't know that was possible. Thanks.

Jon Skeet said:
My normal code is something like:

string line;

while ( (line=myReader.ReadLine()) != null)
{
// Do something with line
}
 
VMI said:
I didn't know that was possible. Thanks.

Just bear in mind that *usually* it's a really bad idea to include
assignment in the middle of something else. However, it's a common
idiom in this case - not just for reading lines, but also reading
chunks of data.
 
Martin said:
myReader.Open();
do
{
/* do what I have to do with myVar */
myVar = myReader.ReadLine();
} while (myVar != null);

Except that where you have "/* do what I have to do with myVar */" - myVar at that point has no value (at least, not one that
has been read from the file).
 
Thats the problem with cut & paste :-) I pasted the comment in the wrong
place. Sorry.

Martin
 
James Curran said:
Nope, still doesn't work... Move the comment to after the ReadLine(),
and on the last pass, you're working on a null string.

myReader.Open();
while (true) {
MyVar myVar = myReader.ReadLine();
if (myVar == null) {
break;
}

// do something with myVar
}

Some might immediately frown at this because we're exiting from the loop
with 'break', but practically, it's simple and readable since it has only
one exit point.

A benefit of this construct is that the variable can be declared in the
inner-most block in which it's required.

Note that declaring the variable inside of the loop is just as performant
as declaring it outside of the loop.
 
Back
Top