0

I wrote an extension method as following

public static void ReadBlock(this Stream stream, Action<string> action, int bufferSize = 8192)
{
    var buffer = new byte[bufferSize];
    while (true)
    {
        var count = stream.Read(buffer, 0, bufferSize);
        if (count == 0) break;
        var text = Encoding.ASCII.GetString(buffer);
        action(text);
    }
}

The problem I have is the last block which is often less than the size of the buffer is not read. and the code returns the n-1 block again (the last buffer).

Can anyone help me to read a stream block by block in the correct way based on buffer size?

1
  • 1
    You'll want to use Encoding.ASCII.GetString(buffer, 0, count) Commented Jun 28, 2021 at 9:14

1 Answer 1

2

The problem is that you're not telling Encoding.GetString how much of the buffer to read.

If you read from the stream and bufferSize bytes are available, then it will fill the buffer up with those bytes.

If you read from the stream and less than bufferSize bytes are available, it will write those bytes to the beginning of the buffer, but won't touch the rest of the buffer. This means the buffer contains count bytes of new data, and the rest is full of the data from your last read.

However, Encoding.GetString doesn't know this, and will just process the entire buffer. Which might be a mix of old and new data.

The solution, of course, is to tell Encoding.GetString how much of the buffer to read:

var text = Encoding.ASCII.GetString(buffer, 0, count);

Note that this approach will only work with ASCII, or other encodings which only ever use 1 byte per character. If you move to UTF-8 or UTF-16, etc, then it'll all go horribly wrong. In this case, you'll want to use a decoder.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.