Copy number of bytes from one Stream to another Stream - CSharp File IO

CSharp examples for File IO:File Command

Description

Copy number of bytes from one Stream to another Stream

Demo Code


using System.IO;/*from  ww  w. j a v  a  2 s .  c  o m*/
using System;

public class Main{
        public static void CopyN(Stream dst, Stream src, long numBytesToCopy)
        {
            long l = src.Position;
            byte[] buffer = new byte[bufferLen];
            long numBytesWritten = 0;
            while (numBytesWritten < numBytesToCopy)
            {
                int len = bufferLen;
                if (numBytesToCopy - numBytesWritten < len)
                {
                    len = (int) (numBytesToCopy - numBytesWritten);
                }
                int n = src.Read(buffer, 0, len);
                if (n == 0)
                {
                    break;
                }
                dst.Write(buffer, 0, n);
                numBytesWritten += n;
            }
            src.Seek(l, SeekOrigin.Begin);
            if (numBytesWritten != numBytesToCopy)
            {
                throw new Exception("StreamUtil.CopyN: nwritten not equal to ncopy");
            }
        }
}

Related Tutorials