为什么块写入长度= 1023而不是1024?

时间:2013-12-13 01:39:16

标签: c# arrays stream binaryfiles

(想知道我是否需要假期)

我正在从一个流写到一个文件。我的块大小是1024

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

我正在测试暂停和恢复操作。我是我的考试,我只写了一个大块。

我的源文件是4096KB。

当我测试写入文件的长度时,它的长度为1023,而不是1024.为什么不是1024?

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

代码参考。

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();
}

1 个答案:

答案 0 :(得分:3)

我建议即使你请求 1024字节,你实际上回到了1023,你可以检查bytesRead来验证这一点。

FileStream实现允许这样做。请参阅文档here

  

Read方法仅在到达结尾后才返回零   流。否则,Read始终从流中读取至少一个字节   回来之前。如果在呼叫时没有来自流的数据   要读取,该方法将阻塞,直到至少一个字节的数据可以   回。 实现可以自由返回比字节数少的字节   即使尚未到达流的末尾也要求。

您的代码仍然正确,因为它只会在返回零时停止读取。但是你不能指望从文件读取的每个块都是1024字节 - 正如你所看到的,情况并非总是如此。