Problem Description: A text file is generated in the background and is provided to the user for download by hyperlink. Click the hyperlink, download Excel file is no problem, but the text file will be opened directly, instead of pop-up download window.
Workaround: Change the hyperlink to LinkButton, and in the Click event, write the text file with the file stream.
Key code:
1 protected voidButton1_Click (Objectsender, EventArgs e)2 {3 stringsFileName =System.IO.Path.GetRandomFileName ();4 stringSgenname ="Friendly.txt";5 6 //You could omit these lines7 //Not want to save the Textfile to the server8 //I have just left them here to demonstrate so you could create the text file9 using(System.IO.StreamWriter SW =NewSystem.IO.StreamWriter (TenServer.MapPath ("textfiles/"+ sFileName +". txt"))) One { A SW. WriteLine (txttext.text); - SW. Close (); - } the -System.IO.FileStream fs =NULL; -FS = System.IO.File.Open (Server.MapPath ("textfiles/"+ -sFileName +". txt"), System.IO.FileMode.Open); + byte[] Btfile =New byte[FS. Length]; -Fs. Read (Btfile,0, Convert.ToInt32 (fs. Length)); + FS. Close (); AResponse.AddHeader ("content-disposition","attachment; Filename="+ at sgenname); -Response.ContentType ="Application/octet-stream"; - Response.BinaryWrite (btfile); - Response.End (); -}
Reference Document: Http://www.codeproject.com/useritems/textfile.asp
ASP. NET hyperlink download text file instead of opening directly in IE