Original: http://www.cnblogs.com/luisliu/p/4253815.html
When our site needs to support downloading large files, if you do not control may cause users to access the download page when the unresponsive, causing the browser to crash. You can avoid this problem by referring to the following code.
A few notes about this code:
1. Divide the data into smaller parts and then move it to the output stream for download to get the data.
2. Specify Response.ContentType according to the file type you downloaded. (this URL can be found for most file types of comparison table: http://tool.oschina.net/commons)
3. Remember to call Response.Flush () every time you finish writing Response
4. Using response.isclientconnected during a cyclic download can help the program find out if the connection is working as soon as possible. If it is not normal, you can abandon the download early to release the server resources that are occupied.
5. After the download is complete, you need to call Response.End () to ensure that the current thread can be terminated at the end.
usingSystem;namespacewebapplication1{ Public Partial classDownloadFile:System.Web.UI.Page {protected voidPage_Load (Objectsender, EventArgs e) {System.IO.Stream IStream=NULL; //Buffer to read 10K bytes in chunk: byte[] buffer =Newbyte[10000]; //Length of the file: intlength; //Total bytes to read. LongdataToRead; //Identify the file to download including its path. stringfilepath = Server.MapPath ("/") +"./files/textfile1.txt"; //Identify the file name. stringfilename =System.IO.Path.GetFileName (filepath); Try { //Open the file.IStream =NewSystem.IO.FileStream (filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System. Io. FileShare.Read); //Total bytes to read.dataToRead =istream.length; Response.Clear (); Response.ClearHeaders (); Response.clearcontent (); Response.ContentType="Text/plain";//Set the file typeResponse.AddHeader ("Content-length", datatoread.tostring ()); Response.AddHeader ("content-disposition","attachment; Filename="+filename); //Read the bytes. while(dataToRead >0) { //Verify that's the client is connected. if(response.isclientconnected) {//Read the data in buffer.Length = istream.read (buffer,0,10000); //Write the data to the current output stream.Response.OutputStream.Write (Buffer,0, length); //Flush The data to the HTML output.Response.Flush (); Buffer=Newbyte[10000]; dataToRead= dataToRead-length; } Else { //Prevent Infinite Loop if user disconnectsdataToRead =-1; } } } Catch(Exception ex) {//Trap the error, if any.Response.Write ("Error:"+Ex. Message); } finally { if(IStream! =NULL) { //Close the file.Istream.close (); } response.end (); } } }}
Reference: http://support2.microsoft.com/kb/812406
ASP. NET download large file implementation (RPM)