Using A Limited Streamreader

Hi,
I’m using the filestream and streamreader to read a file, however I don’t want to read the whole thing.

I only want to read part of the file, not the whole thing.

I’d like to read up to string “abc123” and then “x” characters after it.

I’ve managed to get the result I want by reading the entire file, then doing a few splits, but obviously, if the string I want to look for happens to be 5 characters in, it’s a huge waste to continue reading the rest of the file.

If anyone can offer any advice I’d appreciate it.

Thanks.

steve

you can read a file one byte at the time… how is the file structured?

You can read line by line. as well if your file is in seperate lines

while (reader.Peek() > 0) { reader.ReadLine(); }

then when you find what you are looking for. put a break; in and it will break out of the loop and you can close the stream reader.

Thank you for your suggestions.

I’ve implemented your code as follows:


Dim fs As FileStream = New FileStream(pdfFile, FileMode.Open, FileAccess.Read)
        Dim sr As StreamReader = New StreamReader(fs)

        Dim readFile = sr.ReadToEnd
        While (sr.Peek() > 0)
            readFile = sr.ReadLine
            If readFile.Contains("<</Count") Then
                MsgBox(readFile)
                Exit While
            Else
                readFile = ""
            End If

This works with some files but not with others.

1 particularly large file is giving me trouble.

If I read the file to the end, it finds what I’m looking for, but if it reads line by line, it doesn’t.

I’d like to avoid reading the entire file in these situations if possible.

Any suggestions?

Perhaps joining the last line read to the current one and seeing if it’s there?

I’ve changed:


If readFile.Contains("<</Count") Then
                MsgBox(readFile)
                Exit While
            Else

To:


If readFile.Contains("<</Count") Then
                readFile = readFile & sr.ReadLine
                MsgBox(readFile)
                Exit While
            Else

And it seems to be working.

Was this a sensible solution?

Do not use ReadToEnd(). As that makes it read the entire file. Then you looping through afterwords.