当前位置: 移动技术网 > IT编程>开发语言>c# > C# FileStream实现大文件复制

C# FileStream实现大文件复制

2019年07月18日  | 移动技术网IT编程  | 我要评论

filestream缓冲读取和写入可以提高性能。filestream读取文件的时候,是先将流放入内存,经flush()方法后将内存中(缓冲中)的数据写入文件。如果文件非常大,势必消耗性能。特封装在filehelper中以备不时之需。

参考文章:c# filestream复制大文件。将该文章中提供的代码稍作修改,原文中进行了强制类型转换,如果文件很大,比如4g,就会出现溢出的情况,复制的结果字节丢失严重,导致复制文件和源文件大小不一样。这里修改的代码如下:

public static class filehelper
 {
  /// <summary>
  /// 复制大文件
  /// </summary>
  /// <param name="frompath">源文件的路径</param>
  /// <param name="topath">文件保存的路径</param>
  /// <param name="eachreadlength">每次读取的长度</param>
  /// <returns>是否复制成功</returns>
  public static bool copyfile(string frompath, string topath, int eachreadlength)
  {
   //将源文件 读取成文件流
   filestream fromfile = new filestream(frompath, filemode.open, fileaccess.read);
   //已追加的方式 写入文件流
   filestream tofile = new filestream(topath, filemode.append, fileaccess.write);
   //实际读取的文件长度
   int tocopylength = 0;
   //如果每次读取的长度小于 源文件的长度 分段读取
   if (eachreadlength < fromfile.length)
   {
    byte[] buffer = new byte[eachreadlength];
    long copied = 0;
    while (copied <= fromfile.length - eachreadlength)
    {
     tocopylength = fromfile.read(buffer, 0, eachreadlength);
     fromfile.flush();
     tofile.write(buffer, 0, eachreadlength);
     tofile.flush();
     //流的当前位置
    tofile.position = fromfile.position;
     copied += tocopylength;
     
    }
    int left = (int)(fromfile.length - copied);
    tocopylength = fromfile.read(buffer, 0, left);
    fromfile.flush();
    tofile.write(buffer, 0, left);
    tofile.flush();
 
   }
   else
   {
    //如果每次拷贝的文件长度大于源文件的长度 则将实际文件长度直接拷贝
    byte[] buffer = new byte[fromfile.length];
    fromfile.read(buffer, 0, buffer.length);
    fromfile.flush();
    tofile.write(buffer, 0, buffer.length);
    tofile.flush();
 
   }
   fromfile.close();
   tofile.close();
   return true;
  }
 }

测试代码:

class program
 {
  static void main(string[] args)
  {
 
   stopwatch watch = new stopwatch();
   watch.start();
   if (filehelper.copyfile(@"d:\安装文件\新建文件夹\sqlsvrent_2008r2_chs.iso", @"f:\sqlsvrent_2008r2_chs.iso", 1024 * 1024 * 5))
   {
    watch.stop();
    console.writeline("拷贝完成,耗时:" + watch.elapsed.seconds+"秒");
 
   }
   console.read();
  }
 
 }

结果:

md5校验结果:

文件: d:\安装文件\新建文件夹\sqlsvrent_2008r2_chs.iso
大小: 4662884352 字节
修改时间: 2010年9月3日, 10:41:26
md5: d2bc1d35d987cc6cb8401bfb0a1e1bc9
sha1: 0eeff017b21635df33f33c47e31e911cb23390f7
crc32: 55ac3c56

文件: f:\sqlsvrent_2008r2_chs.iso
大小: 4662884352 字节
修改时间: 2013年9月29日, 10:51:39
md5: d2bc1d35d987cc6cb8401bfb0a1e1bc9
sha1: 0eeff017b21635df33f33c47e31e911cb23390f7
crc32: 55ac3c56

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网