+2  A: 

Not technically an answer to your question, but you could replace all that with:

string[] str = File.ReadAllLines("c:\\error.txt");

Edit (as promised):
Rather than missing a piece, it seems to me that you will have a duplicate of the last part. You're not reading a full 1024 bytes from the file, but you are turning all 1024 bytes into a string and appending it.

Your loop should be like this instead:

int bytesRead;
while ((bytesRead = fr.Read(b, 0, b.Length)) > 0)
{
    data += encoding.GetString(b, 0, bytesRead);
}

Other than that: what Jon said :)

Thorarin
Ha! Great minds think alike ;-)
Eric J.
A: 

Why don't you make your life easier and do this?

string[] str = System.IO.File.ReadAllLines("c:\\error.txt");
Eric J.
+8  A: 

Your code has some subtle errors and problems in:

  • You assume that the whole buffer has been filled by calling GetString(b)
  • You assume that each buffer ends at the end of a character. Use a TextReader (e.g. StreamReader) to read text data, avoiding this sort of problem.
  • You're not closing the file if an exception occurs (use a using directive)
  • You're using string concatenation in a loop: prefer StringBuilder

As others have pointed out, File.ReadAllLines would avoid a lot of this work. There's also File.ReadAllText, and TextReader.ReadToEnd for non-files.

Finally, just use Encoding.UTF8 instead of creating a new instance unless you really need to tweak some options.

Jon Skeet
Thank you very much for so detailed answer!File.ReadAllLines doesn't fit me because the file can grow very large and a lot of processing required to find the line that I need.Creating a StreamReader from a FileStream is just what I looked for.Thank you again!
A: 

You might find it significantly easier to simply use File.ReadLines(). Skip the lines you don't care about, instead of using the position.

int counter = 0;
foreach (string s in File.ReadAllLines(FileName))
{
    ++counter;
    if (counter > 50?)
    {
        Console.WriteLine(s);
    }
}

You could also use the StreamReader, which lets you wrap the stream after setting its position, then use the ReadLine() method.

John Fisher
Supposedly he stored that byte position the previous time he read the file, and now he just wants to read the part that's new. Using the file position would be preferable in that case. Of course, you need to be sure that the file doesn't get overwritten in the meantime (a log being cycled for example).
Thorarin