C# - upload file by chunks - bad last chunk size

余生长醉 提交于 2019-12-11 12:58:38

问题


I am trying to upload large files to 3rd part service by chunks. But I have problem with last chunk. Last chunk would be always smaller then 5mb, but all chunks incl. the last have all the same size - 5mb My code:

int chunkSize = 1024 * 1024 * 5;
using (Stream streamx = new FileStream(file.Path, FileMode.Open, FileAccess.Read))
 {
    byte[] buffer = new byte[chunkSize];

    int bytesRead = 0;
    long bytesToRead = streamx.Length;

    while (bytesToRead > 0)
    {

        int n = streamx.Read(buffer, 0, chunkSize);

        if (n == 0) break;

        // do work on buffer...
        // uploading chunk ....
        var partRequest = HttpHelpers.InvokeHttpRequestStream
            (
                new Uri(endpointUri + "?partNumber=" + i + "&uploadId=" + UploadId),
                "PUT",
                 partHeaders,
                 buffer
            );  // upload buffer


        bytesRead += n;
        bytesToRead -= n;

    }
    streamx.Dispose();
 }   

buffer is uploaded on 3rd party service.


回答1:


Solved, someone posted updated code in comment, but after some seconds deleted this comment. But there was solution. I added this part after

if (n == 0)

this code, which resizes last chunk on the right size

// Let's resize the last incomplete buffer
if (n != buffer.Length)
    Array.Resize(ref buffer, n);

Thank you all.

I post full working code:

int chunkSize = 1024 * 1024 * 5;
using (Stream streamx = new FileStream(file.Path, FileMode.Open, FileAccess.Read))
 {
    byte[] buffer = new byte[chunkSize];

    int bytesRead = 0;
    long bytesToRead = streamx.Length;

    while (bytesToRead > 0)
    {

        int n = streamx.Read(buffer, 0, chunkSize);

        if (n == 0) break;

        // Let's resize the last incomplete buffer
        if (n != buffer.Length)
           Array.Resize(ref buffer, n);

        // do work on buffer...
        // uploading chunk ....
        var partRequest = HttpHelpers.InvokeHttpRequestStream
            (
                new Uri(endpointUri + "?partNumber=" + i + "&uploadId=" + UploadId),
                "PUT",
                 partHeaders,
                 buffer
            );  // upload buffer


        bytesRead += n;
        bytesToRead -= n;

    }

 }   


来源:https://stackoverflow.com/questions/51422506/c-sharp-upload-file-by-chunks-bad-last-chunk-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!