带缓冲的流复制函数

如下是C#针对网络流的, 如果是别的什么流的话貌似需要改改。

public static void streamBufferedCopy(Stream source, Stream target, long size, bool showstatus = true, int bufferSize = 4096)
        {
            byte[] buffer = new byte[bufferSize];
            int currsize = 0;
            long readSize = 0;
            DateTime st = DateTime.Now;
            double time_delta = 0;

            while (size - readSize > 0)
            {
                currsize = source.Read(buffer, 0, bufferSize);
                //target.BeginWrite(buffer, 0, currsize, null, null);
                target.Write(buffer, 0, currsize);
                readSize += currsize;
                time_delta = DateTime.Now.Subtract(st).TotalSeconds;
                if (showstatus)
                {
                    if (time_delta > 0)
                        Console.Write('\r' + "[Downloader] {0}%, {1}KB/s{2}", readSize * 100 / size, (readSize / time_delta / 1024).ToString("0.000"), new string(' ', 10));
                    else
                        Console.Write('\r' + "[Downloader] {0}%, 0KB/s{1}", readSize * 100 / size, new string(' ', 10));
                }
            }

            //if (size - readSize > 0)
            //{
            //    int remainSize = (int)(size - readSize);
            //    currsize = source.Read(buffer, 0, remainSize);
            //    target.Write(buffer, 0, currsize);
            //    readSize += remainSize;
            //}
            if (showstatus)
            {
                time_delta = DateTime.Now.Subtract(st).TotalSeconds;
                if (time_delta > 0)
                    Console.Write('\r' + "[Downloader] {0}%, {1}KB/s{2}\n", readSize * 100 / size, (readSize / time_delta / 1000).ToString("0.000"), new string(' ', 10));
                else
                    Console.Write('\r' + "[Downloader] {0}%, 0KB/s{1}\n", readSize * 100 / size, new string(' ', 10));
            }
            target.Flush();
            target.Close();
        }

在某处发现其实有Stream.CopyTo, 看了看, 貌似是差不多实现的。

发表评论

注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

:wink: :twisted: :roll: :oops: :mrgreen: :lol: :idea: :evil: :cry: :arrow: :?: :-| :-x :-o :-P :-D :-? :) :( :!: 8-O 8)

本文链接:https://twd2.me/archives/3320QrCode