5

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?

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
jlodenius
  • 829
  • 2
  • 13
  • 24
  • You need to be more definitive with your question. "*check if a line contains a string before I read it*" - do you mean check if data was read or check that the line contains a particular string? – James Dec 04 '12 at 14:36

4 Answers4

5

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

Sean Airey
  • 6,352
  • 1
  • 20
  • 38
  • Yes, this worked, first two answers read the rows but consumed them as well, this is exacly what I was looking for. Thanks :) – jlodenius Dec 04 '12 at 14:44
  • 2
    4 year later I know, but I'd like to point out that `Peek()` doesn't work as expected with a `StreamReader` is used with a `NetworkStream` – Xander Luciano Feb 08 '17 at 22:34
4
String row;
while((row=reader.ReadLine())!=null){
    array[i]=row;
}

Should work.

4

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;
}
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
1
while (!reader.EndOfStream)
{
    array[i] = reader.ReadLine();
}
Sracanis
  • 490
  • 5
  • 25
  • Dear downvoter, can you please explain why this answer is not useful? for more details you can check the following link [StreamReader.EndOfStream](https://learn.microsoft.com/en-us/dotnet/api/system.io.streamreader.endofstream?view=netcore-3.1) – Sracanis Jul 14 '20 at 00:55