File stream download ASP. NET

Source: Internet
Author: User

Using System. IO
Void Download ()
{
System. IO. FileStream r = new System. IO. FileStream (FileName, System. IO. FileMode. Open); // File Download instantiation
// Set basic information
Response. Buffer = false;
Response. AddHeader ("Connection", "Keep-Alive ");
Response. ContentType = "application/octet-stream ";
Response. addHeader ("Content-Disposition", "attachment; filename =" + System. IO. path. getFileName (FileName); // if the file name is a Chinese character, it is a chip by default in the browser. You should add HttpUtility. urlEncode (filename)
Response. AddHeader ("Content-Length", r. Length. ToString ());
While (true) // if the file is greater than the buffer, the file is loaded multiple times through the while LOOP
{
// Open the buffer space www.2cto.com
Byte [] buffer = new byte [1024]; // reads file data
Int leng = r. Read (buffer, 0, 1024 );
If (leng = 0) // end at the end of the file
Break;
If (leng = 1024) // read the file data length is equal to the buffer length, directly write the buffer data
Response. BinaryWrite (buffer); // send data streams to the client
Else
{
// Read the file data is smaller than the buffer, and the buffer size is redefined. It is only used to read the last data block of the file.
Byte [] B = new byte [leng]; for (int I = 0; I <leng; I ++)
B [I] = buffer [I];
Response. BinaryWrite (B );
}
}
R. Close (); // Close the downloaded file
Response. End (); // End object download
}

From hcstudio
 

Related Article

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.