Why my code throws thread aborted error?

470 Views Asked by At

I am using this code to download file but it throws error. Please help me in handling it.

Thread was being aborted.

protected void Download_Click(object sender, EventArgs e)
{
    try
    {
        string filePath = Convert.ToString(Attachment);
        string fullFilePath = ("../../SiteImages/" + "donald.jpg");
        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.AddHeader("Content-Disposition", "attachment; filename=\"" + Path.GetFileName(fullFilePath) + "\"");
        Response.ContentType = ContentType;
        Response.TransmitFile(fullFilePath);
        //MngLogs.InsertAuditsInfo("Tender downloaded via" + " " + MngLogs.PageName, MngLogs.UserMacAddress, MngLogs.UserIPAddress, UserID, "Download");
        //Response.End();
    }
    catch (Exception ex)
    {
        Utility.Msg_Error(Master, ex.Message);
    }
}
2

There are 2 best solutions below

4
MasterXD On

Could this download approach work?

try
{
    using (var client = new WebClient())
    {
        client.DownloadFile(urlToFileOnInternet, pathToFileOnComputer);
    }
}
catch (Exception ex)
{
    Utility.Msg_Error(Master, ex.Message);
}

Hope this helps.

0
Lesmian On

Replace

Response.End();

with this:

HttpContext.Current.Response.Flush();
HttpContext.Current.Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();

Response.End(); always throw an exception cause it will abort current thread. You can read more about this behavior here: Is Response.End() considered harmful?, How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download.