Can't download file on LinkButton event clicked

696 views Asked by At

I am trying to download file when user clicks link button event from gridview, but the file is not downloaded.

The code i have when user clicks linkbutton event:

protected void downloadLink_Click1(object sender, EventArgs e)
{
    LinkButton lnkbtn = sender as LinkButton;
    GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;


    string filename = lnkbtn.CommandArgument;

    byte[] mybuffer = Encoding.UTF8.GetBytes(filename);

    Response.Clear();
    Response.ClearHeaders();
    Response.ClearContent();
    //this puts the response to a page
    Response.ContentType = "application/" + "octet-stream";
    Response.AddHeader("Content-disposition", "attachment; filename=" + filename);
    Response.AddHeader("Content-Length", mybuffer.Length.ToString());

    Response.BinaryWrite(mybuffer);
    Response.Flush();
    Response.Close();
    Response.End();

}

1

There are 1 answers

0
Haim Katz On

This code works for me when using a a memory stream to write the file. The difference between my code and yours is that I have a Content-Length header. You may have to get your file size and add this header.

 MemoryStream mybuffer= New MemoryStream(File.ReadAllBytes(filename));
 Response.Clear();
  Response.ClearHeaders();
  Response.ClearContent();
                //this puts the response to a page
  Response.ContentType = "application/" + "octet-stream";
  Response.AddHeader("Content-disposition", "attachment; filename=" + filename); 
  Response.AddHeader("Content-Length", mybuffer.Length.ToString());

  Response.BinaryWrite(mybuffer);
  Response.Flush();
  Response.Close();
   Response.End();