亲宝软件园·资讯

展开

C# FileStream复制大文件

人气:0

即每次复制文件的一小段,以节省总内存开销。当然,本机复制也可以采用.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();

    }

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论