Using C # 's FileStream fragment to copy large files

Source: Internet
Author: User

That is, a small segment of the file is copied each time to save the total memory overhead. Of course, native replication can also be used. NET internal System.IO.File.Copy method.

Code

[Copy to Clipboard]

CODE:

///<summary>
///copy files
///</summary>
///<param name= "FromFile" > Files to be copied </param>
///<param name= "ToFile" > location to save </param>
///<param name= "Lengtheachtime" >       The length of each copy is </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)//If the segmented copy, that is, each copy content is less than the total length of the file
{
byte[] buffer = new B Yte[lengtheachtime];
int copied = 0;
while (copied <= (int) filetocopy.length-lengtheachtime))/copy body part
{
Lengthtoco PY = 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;//copy remaining part
Lengthtocopy = Filetocopy.read ( Buffer, 0, left);
Filetocopy.flush ();
Copytofile.write (buffer, 0, left);
Copytofile.flush ();
}
else//If the overall copy, that is, each copy content is greater than the total length of the file
{
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 ();
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.