# Region -- download file button event -----------------
String FullFileName = Server. Mappath ("~ /"+" Relative path of the file to be downloaded ")
String strFileName = FullFileName. Substring (FullFileName. LastIndexOf ("/") + 1); // get the file name (excluding the path)
FileInfo DownloadFile;
Try
{
DownloadFile = new FileInfo (FullFileName); // you can specify the object to be downloaded.
Response. Clear (); // Clear all content output in the buffer stream
Response. ClearHeaders (); // clear all headers in the buffer stream. If you do not write this statement, the error page is displayed.
Response. Buffer = false; // set the Buffer output to false.
// Set the http mime type of the output stream to application/octet-stream
Response. ContentType = "application/octet-stream ";
// Add the HTTP header to the output stream
Response. AppendHeader ("Content-Disposition ",
"Attachment; filename =" + strFileName + DownloadFile. Extension );
Response. AppendHeader ("Content-Length", DownloadFile. Length. ToString ());
// Write the specified file directly to the HTTP Content output stream.
// It must be noted that WriteFile is not a Write (it hurts me for one night)
Response. WriteFile (DownloadFile. FullName );
Response. Flush (); // send the Current Buffer output to the client
Response. End (); // sends all the current buffer output to the client. This user sometimes has an error. You can try to put this sentence in the last line of the entire function. You can also use HttpContext. Current. ApplicationInstance. CompleteRequest () instead.
}
Catch (Exception err)
{
// Handle errors
// This. labelStatus. Text = "unable to download file:" + sFileName + ", due to:" + err. Message;
}
# Endregion -- download file button event -----------------