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 (); } } }}
A few notes about this code: 1. This data is obtained by dividing the data into smaller parts and then moving it to the output stream for download. 2. Specify Response.ContentType according to the file type you downloaded. (refer to this URL for Oschina to find the table of most file types: http://tool.oschina.net/commons) 3. Remember to call Response.Flush () 4 each time you finish writing Response. 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.
---excerpt from http://www.admin10000.com/document/5999.html
Implementation ideas and codes for ASP. NET large File download