Stream.CopyTo()方法可以保存不完整的流吗? [英] Can Stream.CopyTo() method save the streams incomplete?

查看:104
本文介绍了Stream.CopyTo()方法可以保存不完整的流吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WCF服务,该服务使我可以分块上传文件.我想知道的是,在任何情况下,这段代码都可能导致上传的流仅部分地附加到目标流吗?

I have a WCF service which allows me to upload files in chunks. What I am wondering is could this code can cause the uploaded stream to be only partially appended to the target stream in any case?

我的日志显示所有发送的流都是512000字节(我在客户端设置),到目前为止,我已经发送了9个块中的6个块.但是在服务器上,文件大小为2634325.这意味着发送的最后一个块(第6个)未完全保存.

I have my logs that shows me that all the sent streams are 512000 byte(which I set on client side) and I've sent 6 chunks out of 9 chunks so far. But on server the files size is 2634325. Which means the last chunk sent(6th) is saved incompletely.

什么可能导致这种行为?我应该怎么做才能避免这种情况?

What can be causing this behaviour? What should I do to avoid this?

这是完全安全的,我应该在其他地方寻找该错误吗?

Or is this completely safe, and I should look for the bug in somewhere else?

public void UploadChunk ( RemoteFileChunk file )
{
    /// this file is not touched by anyone else
    var uploadPath = @"C:\some path\some.file";

    using ( var targetStream = new FileStream(uploadPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None) )
    { 
        if ( targetStream.Length == file.ChunkNumber * Helper.ChunkSize )
        {
            /// ---- streaming operation is here ----
            targetStream.Position = targetStream.Length;
            file.Stream.CopyTo(targetStream);
            file.Stream.Close();
            /// -------------------------------------
        }
        else throw new FaultException<DataIntegrityException>(new DataIntegrityException
        {
            CurrentIndex = targetStream.Length,
            RequestedIndex = file.ChunkNumber * Helper.ChunkSize,
            Message = string.Format("{0}th chunk index requested when there already {1} chunks exist.", file.ChunkNumber, targetStream.Length / Helper.ChunkSize)
        });
    }
}

以下是客户端文件上传代码段:

And below is the client side file upload code snippet:

var buffer = new byte[ChunkIndex != NumberOfChunks - 1 ? Helper.ChunkSize : LastPieceLen];

using ( var file = new FileStream(Info.FullName, FileMode.Open, FileAccess.Read, FileShare.None) )
{
    file.Position = (long)ChunkIndex * Helper.ChunkSize;
    file.Read(buffer, 0, buffer.Length);
}

var chunk = new MemoryStream(buffer);

chunk.Position = 0;
Service.StreamingEnd.UploadChunk(new RemoteFileChunk(FileId, CF.Id, VersionDate, ChunkIndex, chunk.Length, Sessions.Get(), chunk));

推荐答案

看看那条if语句-是否保证最终块的大小恰好是块的大小?如果您上传的文件大小不是块大小的倍数,会发生什么?

Have a look at that if statement -- is the final chunk guaranteed to be exactly the chunk size? What happens if the size of the file you are uploading is not a multiple of the chunk size?

这篇关于Stream.CopyTo()方法可以保存不完整的流吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆