Stream.CopyTo not copying any stream data

15,610

Solution 1

Stream.CopyTo() starts copying from the stream's current Position. Which probably isn't 0 after that LoadIntoStream() call. Since it is a MemoryStream, you can simply fix it like this:

    await dataSource.LoadIntoStream(sourceStream);
    sourceStream.Position = 0;
    sourceStream.CopyTo(targetStream);

Solution 2

Set sourceStream.Position = 0 before copying it. The copy will copy from the current position to the end of the stream.

Solution 3

As other have said the Position is probably no longer 0. You can't always set the Position back to 0 though, such as for Network and Compressed streams. You should check the stream.CanSeek property before doing any operations and if it is false then copy the stream to a new MemoryStream first (which can be seeked) and then after each operation which changes the position set the Position back to 0.

Share:
15,610

Related videos on Youtube

Herdo
Author by

Herdo

Updated on June 18, 2022

Comments

  • Herdo
    Herdo almost 2 years

    I'm having an issue with copying data from a MemoryStream into a Stream inside a ZipArchive. The following is NOT working - it returns only 114 bytes:

    GetDataAsByteArray(IDataSource dataSource)
    {
        using (var zipStream = new MemoryStream())
        {
            using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
            {
                var file = archive.CreateEntry("compressed.file");
                using (var targetStream = file.Open())
                {
                    using (var sourceStream = new MemoryStream())
                    {
                        await dataSource.LoadIntoStream(sourceStream);
                        sourceStream.CopyTo(targetStream);
                    }
                }
            }
            var result = zipStream.ToArray();
            zipStream.Close();
            return result;
        }
    }
    

    However, using the implementation below for the "copy"-process, all 1103 bytes are written to the array/memory stream:

    await targetStream.WriteAsync(sourceStream.ToArray(), 0, (int) sourceStream.Length);
    

    I'm wondering why the CopyTo yields less bytes. Also I'm feeling unsecure with the cast to Int32 in the second implementation.

    FYI: Comparing the byte array: It looks like only the header and footer of the zip file were written by the first implementation.

  • hardba11
    hardba11 over 3 years
    Thank you Hans!! 6 years later, still a helpful post.