jlodenius
jlodenius

Reputation: 829

Check if a StreamReader can read another line

I need to check if a line contains a string before I read it, I want to do this using a while loop something like this

    while(reader.ReadLine() != null)
    {
        array[i] = reader.ReadLine();
    }

This obviously doesen't work, so how can I do this selection?

Upvotes: 5

Views: 10072

Answers (4)

Sracanis
Sracanis

Reputation: 490

while (!reader.EndOfStream)
{
    array[i] = reader.ReadLine();
}

Upvotes: 1

Sean Airey
Sean Airey

Reputation: 6372

Try using the Peek method:

while (reader.Peek() >= 0)
{
    array[i] = reader.ReadLine();
}

Docs: http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline.aspx and http://msdn.microsoft.com/en-us/library/system.io.streamreader.peek.aspx

Upvotes: 5

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236248

StreamReader.ReadLine reads a line of characters from the current stream, also the reader's position in the underlying Stream object is advanced by the number of characters the method was able to read. So, if you call this method second time, you will read next line from underlying stream. Solution is simple - save line to local variable.

string line;
while((line = reader.ReadLine()) != null)
{
   array[i] = line;
}

Upvotes: 4

TinyPinkSaxophone
TinyPinkSaxophone

Reputation: 130

String row;
while((row=reader.ReadLine())!=null){
    array[i]=row;
}

Should work.

Upvotes: 4

Related Questions