Microsoft.Http.StreamExtensions.CopyAndCloseSource C# (CSharp) Method

CopyAndCloseSource() public static method

public static CopyAndCloseSource ( this source, Stream destination, long size ) : long
source this
destination Stream
size long
return long
        public static long CopyAndCloseSource(this Stream source, Stream destination, long? size)
        {
            int reads = 0;
            long total = 0;
            int bufferSize;
            using (source)
            {
                if (size.HasValue && size < 0)
                {
                    size = null;
                }
                if (size == null || (size.HasValue && size.Value > maxSize))
                {
                    bufferSize = maxSize; // max socket read
                }
                else
                {
                    bufferSize = (int)size.Value;
                }
                byte[] buffer;
                int got;

                if (destination == null)
                {
                    buffer = drainBuffer;
                    while ((got = source.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ++reads;
                        total += got;
                        if (size != null && total == size.Value)
                        {
                            break;
                        }
                    }
                }
                else
                {
                    buffer = new byte[bufferSize];

                    while ((got = source.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ++reads;
                        destination.Write(buffer, 0, got);
                        total += got;
                        if (size != null && total == size.Value)
                        {
                            break;
                        }
                    }

                    destination.Flush();
                }
            }
            return total;
        }
        public static byte[] ReadAllBytes(this Stream source, long? length)

Usage Example

Example #1
0
 public override void WriteTo(Stream other, long?length)
 {
     using (this.stream)
     {
         closed = true;
         StreamExtensions.CopyAndCloseSource(this.stream, other, length);
     }
 }