Wednesday, March 6, 2024

How to download a file in asp.net c# linkbutton

aspx

 string filePath = (sender as LinkButton).CommandArgument;

            Response.ContentType = ContentType;

            Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));

            Response.WriteFile(filePath);

            Response.End();

aspx.cs


<asp:LinkButton ID="lnkDownload" runat="server" CausesValidation="False" CommandArgument='<%# Eval("DocumentFilePath") %>'

                                                                            CommandName="Download" OnClick="lnkDownload_Click" Text='<%# Eval("DocumentFilePath") %>' />



or



if (e.CommandName == "Download")

            {

                string filePath = "~\\cbisupportfiles\\Rent\\" + "Hindi.pdf";

                //string filePath = "~//cbisupportfiles//Rent//" + "Roles05232018052335.txt";


                if (!string.IsNullOrEmpty(filePath))

                {                   


                    string filename = "Hindi.pdf";

                    string Filpath = Server.MapPath("~/cbisupportfiles/Rent/" + filename);

                    DownLoad(Filpath);

                   

                }



public void DownLoad(string FName)

        {

            string path = FName;

            System.IO.FileInfo file = new System.IO.FileInfo(path);

            if (file.Exists)

            {

                Response.Clear();

                Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); Response.AddHeader("Content-Length", file.Length.ToString());

                Response.ContentType = "application/octet-stream"; // download […]

                Response.WriteFile(path);

                Response.End();

            }

        }

No comments:

Post a Comment