欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# FileStream复制大文件功能

程序员文章站 2023-11-01 09:08:34
filestream缓冲读取和写入可以提高性能。每次复制文件的一小段,以节省总内存开销。当然,本机复制也可以采用.net内部的system.io.file.copy方法。...

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

filestream读取文件的时候,是先讲流放入内存,经flash()方法后将内存中(缓冲中)的数据写入文件。如果文件非常大,势必消耗性能。特封装在filehelper中以备不时之需。强制类型转换,如果文件很大,比如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();
    }
  }


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