System.IO.MemoryStream.CopyTo C# (CSharp) Method

CopyTo() public method

public CopyTo ( Stream destination, int bufferSize ) : void
destination Stream
bufferSize int
return void
        public override void CopyTo(Stream destination, int bufferSize)
        {
            // Since we did not originally override this method, validate the arguments
            // the same way Stream does for back-compat.
            StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);

            // If we have been inherited into a subclass, the following implementation could be incorrect
            // since it does not call through to Read() which a subclass might have overridden.  
            // To be safe we will only use this implementation in cases where we know it is safe to do so,
            // and delegate to our base class (which will call into Read) when we are not sure.
            if (GetType() != typeof(MemoryStream))
            {
                base.CopyTo(destination, bufferSize);
                return;
            }
            
            int originalPosition = _position;

            // Seek to the end of the MemoryStream.
            int remaining = InternalEmulateRead(_length - originalPosition);

            // If we were already at or past the end, there's no copying to do so just quit.
            if (remaining > 0)
            {
                // Call Write() on the other Stream, using our internal buffer and avoiding any
                // intermediary allocations.
                destination.Write(_buffer, originalPosition, remaining);
            }
        }

Usage Example

Exemplo n.º 1
0
        public unsafe void CopyTo1()
        {
            const int bufferSize = 10;
            byte* buffer = (byte*)Marshal.AllocHGlobal(bufferSize);

            try
            {
                var s = new MemoryStream(new byte[] { 0, 1, 2, 3, 4 });

                InvalidateMemory(buffer, bufferSize);
                s.Seek(0, SeekOrigin.Begin);
                s.CopyTo(buffer, 3);
                Assert.Equal(new byte[] { 0, 1, 2 }, ReadBuffer(buffer, bufferSize));

                InvalidateMemory(buffer, bufferSize);
                s.Seek(0, SeekOrigin.Begin);
                s.CopyTo(buffer, 0);
                Assert.Equal(new byte[0], ReadBuffer(buffer, bufferSize));

                InvalidateMemory(buffer, bufferSize);
                s.Seek(0, SeekOrigin.Begin);
                s.CopyTo(buffer, 5);
                Assert.Equal(new byte[] { 0, 1, 2, 3, 4 }, ReadBuffer(buffer, bufferSize));

                Assert.Throws<IOException>(() => s.CopyTo(buffer, 6));
            }
            finally
            {
                Marshal.FreeHGlobal((IntPtr)buffer);
            }
        }
All Usage Examples Of System.IO.MemoryStream::CopyTo