'how to create a hyperlink for file download in asp.net?

I have some files stored on my machine. When a user wants to generate a link the page should generate a hyperlink. This hyperlink can be used by any other user so as to download the file



Solution 1:[1]

Have a LinkButton and for the click event do the following

your aspx file will have the following

   <asp:LinkButton runat="server" OnClick="btnDownload_Click" Text="Download"/>

Your code behind will have the following

 protected void btnDownload_Click(object sender, EventArgs e)
    {
        try
        {


            var fileInBytes = Encoding.UTF8.GetBytes("Your file text");
            using (var stream = new MemoryStream(fileInBytes))
            {
                long dataLengthToRead = stream.Length;
                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();
                Response.BufferOutput = true;
                Response.ContentType = "text/xml"; /// if it is text or xml
                Response.AddHeader("Content-Disposition", "attachment; filename=" + "yourfilename");
                Response.AddHeader("Content-Length", dataLengthToRead.ToString());
                stream.WriteTo(Response.OutputStream);
                Response.Flush();
                Response.Close();
            }
            Response.End();
            }
        }
        catch (Exception)
        {

        }
    }

Solution 2:[2]

you can direct link the hyperlink with the file if you know the address but this is limited by the browser. eg. if pdf reader is installed on the client then the pdf will not be downloaded instead it will be shown. A good solution would be to have a seperate page for downloading files. just pass filename in querystring and in the pageload event just outpit the file in response stream.This way you can use url say dwnld.aspx?filename.ext

Now you can generate urls via the above logic.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ratna