asp.net directly save files to client

Source: Internet
Author: User
Asp.net| client's usual file downloads are implemented by jumping out of the window, but there is a problem that will be intercepted by the advertising interception software, and I have a very headache, so look for a better solution. After reading the paper with Response.BinaryWrite, I feel that it is possible.
The following code implements this functionality, resolves the file format problem (that is, only the stream is output, but the file format is not correctly recognized), and the file is read from the registry contenttype

1/**////<summary>
2///Download files
3///</summary>
4///<param name= "filename" > File Physical Address </param>
5 protected void DownloadFile (string filename)
6 {
7
8 String savefilename = "Test.xls";
9 int intstart = filename. LastIndexOf ("\") +1;
Ten savefilename = filename. Substring (Intstart,filename. Length-intstart);
11
System.IO.FileInfo fi=new System.IO.FileInfo (filename);
Fileextname=fi string. Extension;
String default_content_type = "Application/unknown";
RegistryKey Regkey,fileextkey;
String Filecontenttype;
Try
18 {
Regkey=registry.classesroot;
Fileextkey=regkey. OpenSubKey (Fileextname);
Filecontenttype=fileextkey. GetValue ("Content Type", Default_content_type). ToString ();
22}
Catch
24 {
Filecontenttype=default_content_type;
26}
27
28
Response.Clear ();
Response.Charset = "Utf-8";
Response.buffer= true;
this. EnableViewState = false;
response.contentencoding = System.Text.Encoding.UTF8;
34
Response.appendheader ("Content-disposition", "attachment;filename=" + savefilename);
Response.contenttype=filecontenttype;
37
Response.WriteFile (filename);
Response.Flush ();
Response.close ();
41
Response.End ();
43}

The effect chart is as follows:




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.