Search code examples
c#filestream

C#: FileStream.Read() doesn't read the file up to the end, but returns 0


Here is how i do it:

static void Main(string[] args)
{
    string FileName = "c:\\error.txt";
    long FilePosition = 137647;

    FileStream fr = new FileStream(FileName, FileMode.Open);
    byte[] b = new byte[1024];
    string data = string.Empty;
    fr.Seek(FilePosition, SeekOrigin.Begin);
    UTF8Encoding encoding = new UTF8Encoding();

    while (fr.Read(b, 0, b.Length) > 0)
    {
        data += encoding.GetString(b);
    }
    fr.Close();
    string[] str = data.Split(new string[] { "\r\n" }, StringSplitOptions.None);
    foreach (string s in str)
    {
        Console.WriteLine(s);
    }
    Console.ReadKey();
}

The str array ends with these lines:

***** History for hand T5-2847880-18 (TOURNAMENT: S-976-46079) *****
Start hand: Tue Aug 11 18:14

but there are more lines in the file.

I've uploaded error.txt to sendspace: http://www.sendspace.com/file/5vgjtn And here is the full console output: the_same_site/file/k05x3a

Please help! I'm really clueless here. Thanks in advance!


Solution

  • 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.