代码之家  ›  专栏  ›  技术社区  ›  sboisse

从Amazon AWS S3下载对象时仅部分读取流[重复]

  •  2
  • sboisse  · 技术社区  · 6 年前

    Amazon.S3.AmazonS3Client 带着一个 Amazon.S3.Transfer.TransferUtility ,但在这两种情况下,实际上只有第一个字节被复制到缓冲区中。

    var stream = await _transferUtility.OpenStreamAsync(BucketName, key);
    using (stream)
    {
        byte[] content = new byte[stream.Length];
        stream.Read(content, 0, content.Length);
        // Here content should contain all the data from the stream, but only the first 8192 bytes are actually populated.
    }
    

    调试时,我看到流类型是 Amazon.Runtime.Internal.Util.Md5Stream ,在流中,在呼叫之前 Read() 财产 CurrentPosition = 0. 电话打完后, 变成8192,这似乎确实表明只读取了前8K个数据。总数 Length 这条河的流量是104042。

    stream.Read() 当前位置 当前位置 不是公共属性,并且我无法在代码中访问它来创建 while() 循环(必须编写这样的循环才能读取所有数据似乎有点笨拙)。

    我试过打电话 stream.Flush()

    编辑1

    我已经修改了代码,因此它可以执行以下操作:

    var stream = await _transferUtility.OpenStreamAsync(BucketName, key);
    using (stream)
    {
        byte[] content = new byte[stream.Length];
        var bytesRead = 0;
    
        while (bytesRead < stream.Length)
            bytesRead += stream.Read(content, bytesRead, content.Length - bytesRead);
    }
    

    而且很有效。但看起来还是很笨重。我这样做正常吗?

    编辑2

    CopyTo() . 所以不再有笨重的循环,如果 读取() 在读取整个流之前开始返回0:

    var stream = await _transferUtility.OpenStreamAsync(BucketName, key);
    using (stream)
    {
        using (var memoryStream = new MemoryStream((int)stream.Length))
        {
            stream.CopyTo(memoryStream);
            var myBuffer = memoryStream.GetBuffer();
        }
    }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   John Hanley    6 年前

    stream.Read() 返回读取的字节数。然后可以跟踪读取的总字节数,直到到达文件末尾( content.Length

    也可以循环直到返回值为0 error / no more bytes left

    您需要跟踪内容缓冲区的当前偏移量,这样就不会覆盖每个调用的数据。