本文介绍了C# - 按块上传文件 - 最后一个块大小不好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按块将大文件上传到第 3 部分服务.但我对最后一块有问题.最后一个块总是小于 5mb,但所有块都包括.最后一个大小相同 - 5mb我的代码:

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

缓冲区上传到第 3 方服务.

buffer is uploaded on 3rd party service.

推荐答案

已解决,有人在评论中发布了更新的代码,但几秒钟后删除了此评论.但是有解决方案.我在

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

谢谢大家.

我发布了完整的工作代码:

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;

    }

 }

这篇关于C# - 按块上传文件 - 最后一个块大小不好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-26 11:58
查看更多