即每次復制文件的一小段,以節省總內存開銷。當然,本機復制也可以采用.Net內部的System.IO.File.Copy方法。
Code
[copy to clipboard]
CODE:
/// <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();
}