Question

(wondering if i need a holiday)

I am writing from a stream to a file. My chunk size is 1024

    int chunkSize = 1024;
    byte[] buffer = new byte[chunkSize];

I am testing pause and resume operations. Im my test, I am only writing one chunk.

My source file is 4096KB.

When I test how long the written file is, it has a length of 1023, not 1024. Why is it not 1024?

FileInfo partFile = new FileInfo(fullPath);
Console.Write(partFile.Length); //1023, not 1024!?

Code reference.

int chunkSize = 1024;
byte[] buffer = new byte[chunkSize];
int chunkCount = 0;

bool streamComplete = true;

using (FileStream writeStream = new FileStream(tempFullPath, FileMode.Append, FileAccess.Write))
{

    do
    {
        chunkCount++;

        if (request.MaxChunks != 0 && request.MaxChunks < chunkCount)
        {
            streamComplete = false;
            break;
        }

        int bytesRead = request.FileByteStream.Read(buffer, 0, chunkSize);
        if (bytesRead == 0) break;

        writeStream.Write(buffer, 0, bytesRead);
    } while (true);


    writeStream.Close();
}
Was it helpful?

Solution

I'm going to suggest that even though you requested 1024 bytes, you actually got back 1023, and you can check bytesRead to verify this.

This is allowed by FileStream implementations. See documentation here.

The Read method returns zero only after reaching the end of the stream. Otherwise, Read always reads at least one byte from the stream before returning. If no data is available from the stream upon a call to Read, the method will block until at least one byte of data can be returned. An implementation is free to return fewer bytes than requested even if the end of the stream has not been reached.

Your code is still correct, in that it only stops reading when zero is returned. But you can't expect every chunk read from the file to be exactly 1024 bytes - as you can see, it's not necessarily always the case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top