(转) C# FileStream复制大文件


                    即每次复制文件的一小段,以节省总内存开销。当然,本机复制也可以采用.NET内部的System.IO.File.Copy方法。

        /// <summary>

        /// 复制文件

        /// </summary>

        /// <param name="fromFile">要复制的文件</param>

        /// <param name="toFile">要保存的位置</param>

        /// <param name="lengthEachTime">每次复制的长度</param>

        private void CopyFile(string fromFile, string toFile, int lengthEachTime)

        {

            FileStream fileToCopy = new FileStream(fromFile, FileMode.Open, FileAccess.Read);

            FileStream copyToFile = new FileStream(toFile, FileMode.Append, FileAccess.Write);

            int lengthToCopy;

            if (lengthEachTime < fileToCopy.Length)//如果分段拷贝,即每次拷贝内容小于文件总长度

            {

                byte[] buffer = new byte[lengthEachTime];

                int copied = 0;

                while (copied <= ((int)fileToCopy.Length - lengthEachTime))//拷贝主体部分

                {

                    lengthToCopy = fileToCopy.Read(buffer, 0, lengthEachTime);

                    fileToCopy.Flush();

                    copyToFile.Write(buffer, 0, lengthEachTime);

                    copyToFile.Flush();

                    copyToFile.Position = fileToCopy.Position;

                    copied += lengthToCopy;

                }

                int left = (int)fileToCopy.Length - copied;//拷贝剩余部分

                lengthToCopy = fileToCopy.Read(buffer, 0, left);

                fileToCopy.Flush();

                copyToFile.Write(buffer, 0, left);

                copyToFile.Flush();

            }

            else//如果整体拷贝,即每次拷贝内容大于文件总长度

            {

                byte[] buffer = new byte[fileToCopy.Length];

                fileToCopy.Read(buffer,0,(int)fileToCopy.Length);

                fileToCopy.Flush();

                copyToFile.Write(buffer, 0, (int)fileToCopy.Length);

                copyToFile.Flush();

            }

            fileToCopy.Close();

            copyToFile.Close();

        }

转载于:https://www.cnblogs.com/yangxiaohu1/archive/2008/06/20/1226949.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值