) C # copy a large file using filestream

Source: Internet
Author: User
That is, a small segment of the file is copied each time to save the total memory overhead. Of course, local replication can also adopt the system. Io. file. COPY method in. net.

/// <Summary>

/// Copy an object

/// </Summary>

/// <Param name = "fromfile"> file to be copied </param>

/// <Param name = "tofile"> location to be saved </param>

/// <Param name = "lengtheachtime"> length of each copy </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 multipart copy is performed, the content of each copy is smaller than the total length of the file.

{

Byte [] buffer = new byte [lengtheachtime];

Int copied = 0;

While (copied <= (INT) filetocopy. Length-lengtheachtime) // copy the subject part

{

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; // copy the remaining part

Lengthtocopy = filetocopy. Read (buffer, 0, left );

Filetocopy. Flush ();

Copytofile. Write (buffer, 0, left );

Copytofile. Flush ();

}

Else // if the overall copy, that is, the content of each copy 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.