Monday 13 October 2014

Downloading files from server folder in C# on link button clicked Event which is inside GridView

     


              
 protected void lnk_attach4_Click(object sender, EventArgs e)
    {
        try
        {
            LinkButton _lnk = (LinkButton)sender;
            GridViewRow _row = (GridViewRow)_lnk.NamingContainer;
            int _i = Convert.ToInt32(_row.RowIndex);
            int _reqID = Convert.ToInt32(gv_hrmrequest.DataKeys[_i][0].ToString());

            string _LogPath = ConfigurationManager.AppSettings["Docs"].ToString();
            string _filename1 = _LogPath + _reqID + "_4_" + _lnk.Text;

            if (_lnk.Text != string.Empty)
            {
                if (_lnk.Text.EndsWith(".txt"))
                {
                    Response.ContentType = "application/txt";
                }
                else if (_lnk.Text.EndsWith(".pdf"))
                {
                    Response.ContentType = "application/pdf";
                }
                else if (_lnk.Text.EndsWith(".docx"))
                {
                    Response.ContentType = "application/docx";
                }
                else
                {
                    Response.ContentType = "image/jpg";
                }

                string filePath = _lnk.Text;

                Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
                Response.TransmitFile(_filename1);
                Response.End();
            }
        }
        catch (Exception ex)
        {

        }
        finally
        {

        }
    }