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

C# FileStream复制大文件

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

本文实例为大家分享了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();

    }

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

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

相关文章:

验证码:
移动技术网