ASP. NET File Download Code

Source: Internet
Author: User
1   Public   Static   Void Download (page, String Filename)
2 {
3 Try
4 {
5 System. Io. filestream R =   New System. Io. filestream (filename, system. Io. filemode. Open );
6 // Set Basic Information
7 Page. response. Buffer =   False ;
8 Page. response. addheader ( " Connection " , " Keep-alive " );
9 Page. response. contenttype =   " Application/octet-stream " ;
10 Page. response. addheader ( " Content-Disposition " , " Attachment; filename = "   + System. Io. Path. getfilename (filename ));
11 Page. response. addheader ( " Content-Length " , R. length. tostring ());
12 While ( True )
13 {
14 // Buffer space opening
15 Byte [] Buffer =   New   Byte [ 1024 ];
16 // Read File data
17 Int Leng = R. Read (buffer, 0 , 1024 );
18 If (Leng =   0 ) // End at the end of the file
19 Break ;
20 If (Leng =   1024 ) // The read file data length is equal to the buffer length, and the buffer data is directly written
21 Page. response. binarywrite (buffer );
22 Else
23 {
24 // Reading 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.
25 Byte [] B =   New   Byte [Leng];
26 For ( Int I =   0 ; I < Leng; I ++ )
27 B [I] = Buffer [I];
28 Page. response. binarywrite (B );
29 Break ;
30 }
31 }
32 R. Close (); // Close File Download
33 Httpcontext. Current. applicationinstance. completerequest (); // End File Download
34 Page. response. Flush ();
35 Page. response. Close ();
36 }
37 Catch (System. Exception ex)
38 {
39ThrowEx;
40}
41 }

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.