Can Stream.CopyTo() method save the streams incomp

2019-03-22 03:10发布

问题:

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?

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

回答1:

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?