0

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);
    }
}
Cuckoo
  • 177
  • 1
  • 2
  • 10
  • Where did you get the error? `Reponse.End()` always throws a `ThreadAbortException`. Have a look at [this](http://stackoverflow.com/questions/20988445/how-to-avoid-response-end-thread-was-being-aborted-exception-during-the-exce) and [this](http://stackoverflow.com/questions/5834049/what-causes-thread-was-being-aborted-exception-to-happen-at-random-and-show-th) post. – diiN__________ Jul 28 '16 at 09:32
  • yes same place and i removed it but still it doesn't download a file – Cuckoo Jul 28 '16 at 09:33
  • and doesn't throw error but still doesn't download a file – Cuckoo Jul 28 '16 at 09:33
  • Does this answer your question? [ThreadAbortException (WebClient using DownloadFile to grab file from server)](https://stackoverflow.com/questions/2542664/threadabortexception-webclient-using-downloadfile-to-grab-file-from-server) – TylerH Jul 12 '22 at 13:51

2 Answers2

0

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.

MasterXD
  • 804
  • 1
  • 11
  • 18
0

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.

Community
  • 1
  • 1
Lesmian
  • 3,932
  • 1
  • 17
  • 28