如何在c#中使用文件流复制大文件

  介绍

这期内容当中小编将会给大家带来有关如何在c#中使用文件流复制大文件,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

文件流缓冲读取和写入可以提高性能。每次复制文件的一小段,以节省总内存开销。当然,本机复制也可以采用。net内部的System.IO.File.Copy方法。

文件流读取文件的时候,是先讲流放入内存,经Flash()方法后将内存中(缓冲中)的数据写入文件。如果文件非常大,势必消耗性能。特封装在FileHelper中以备不时之需。强制类型转换,如果文件很大,比如4 g,就会出现溢出的情况,复制的结果字节丢失严重,导致复制文件和源文件大小不一样。这里修改的代码如下:

public  static  class  FileHelper   {才能   ,,,///,& lt; summary>   ,,,///,复制大文件   ,,,///,& lt;/summary>   ,,,///,& lt; param  name=癴romPath"在源文件的路径& lt;/param>   ,,,///,& lt; param  name=皌oPath"在文件保存的路径& lt;/param>   ,,,///,& lt; param  name=癳achReadLength"在每次读取的长度& lt;/param>   ,,,///,& lt; returns>是否复制成功& lt;/returns>   ,,,public  static  bool 拷贝文件(string  fromPath, string  toPath,, int  eachReadLength)   ,,,{   ,,,,,//将源文件,读取成文件流   ,,,,,FileStream  fromFile =, new 文件流(fromPath, FileMode.Open,, FileAccess.Read);   ,,,,,//已追加的方式,写入文件流   ,,,,,FileStream  toFile =, new 文件流(toPath, FileMode.Append,, FileAccess.Write);   ,,,,,//实际读取的文件长度   ,,,,,int  toCopyLength =, 0;   ,,,,,//如果每次读取的长度小于,源文件的长度,分段读取   ,,,,,if  (eachReadLength  & lt;, fromFile.Length)   ,,,,,{   ,,,,,,,byte [], buffer =, new 字节(eachReadLength);   ,,,,,,,long  copied =, 0;   ,,,,,,,while  (copied  & lt;=, fromFile.Length 作用;eachReadLength)   ,,,,,,,{   ,,,,,,,,,toCopyLength =, fromFile.Read(缓冲,0,eachReadLength);   ,,,,,,,,,fromFile.Flush ();   ,,,,,,,,,toFile.Write(缓冲,0,eachReadLength);   ,,,,,,,,,toFile.Flush ();   ,,,,,,,,,//流的当前位置   ,,,,,,,,,toFile.Position =, fromFile.Position;   ,,,,,,,,,copied  +=, toCopyLength;   ,,,,,,,}   ,,,,,,,int  left =, (int) (fromFile.Length 安康;复制);   ,,,,,,,toCopyLength =, fromFile.Read(缓冲区,,0,,左);   ,,,,,,,fromFile.Flush ();   ,,,,,,,toFile.Write(缓冲区,,0,,左);   ,,,,,,,toFile.Flush ();   ,   ,,,,,}   ,,,,,   ,,,,,{   ,,,,,,,//如果每次拷贝的文件长度大于源文件的长度,则将实际文件长度直接拷贝   ,,,,,,,byte [], buffer =, new 字节(fromFile.Length);   ,,,,,,,fromFile.Read(缓冲,0,buffer.Length);   ,,,,,,,fromFile.Flush ();   ,,,,,,,toFile.Write(缓冲,0,buffer.Length);   ,,,,,,,toFile.Flush ();   ,   ,,,,,}   ,,,,,fromFile.Close ();   ,,,,,toFile.Close ();   ,,,,,return 真实;   ,,,}   以前,,}

测试代码:

class 程序   {才能   ,,,static  void  Main (string [], args)   ,,,{   ,   ,,,,,Stopwatch  watch =, new 秒表();   ,,,,,watch.Start ();   ,,,,,if  (FileHelper.CopyFile (@" D: \安装文件\新建文件夹\ SQLSVRENT_2008R2_CHS.iso",, @" F: \ SQLSVRENT_2008R2_CHS.iso",, 1024, *, 1024, *, 5))   ,,,,,{   ,,,,,,,watch.Stop ();   null   null   null   null   null

如何在c#中使用文件流复制大文件