简体   繁体   中英

Visual Studio 2010 ASP.net c# Download file for hyper link at runtime not working

I have a Visual Studio 2010 ASP.net web site using c#.

I can display all files for a specific folder location at runtime on a Web Page:-

        protected void Page_Load(object sender, EventArgs e)
    {
        DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/Downloads"));
        int i = 0;
        foreach (FileInfo fi in di.GetFiles())
        {
            HyperLink HL = new HyperLink();
            HL.ID = "HyperLink" + i++;
            HL.Text = fi.Name;
            HL.NavigateUrl = "FileDownloads.aspx?file=" + fi.Name;
            Page.Controls.Add(HL);
            Page.Controls.Add(new LiteralControl("<br/>"));
        }
    }

The above code displays the files as a hyperlink on the Web Page but when I click on any link the page seems to refresh and not download the specific file?

Can I assign a password to the links?

Would a Android phone user experience the same behaviors as a windows web browser user?

Any examples would be welcomed.

tia

As a work around I now use LinkButtons.

First I manually placed a number of PlaceHolder controls on the web page.

On the Page Load event I then search a specific web site folder for any files. If any file found then create a LinkButton and assign the method TransmitFile to the LinkButton Command event.

 protected void Page_Load(object sender, EventArgs e)
    {
        DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/Downloads"));
        int i = 0;
        foreach (FileInfo fi in di.GetFiles())
        {
            LinkButton LB = new LinkButton();
            LB.ID = "LinkButton" + i++;
            LB.Text = fi.Name;                
            LB.CommandName = Convert.ToString(i); 
            LB.Command += new CommandEventHandler(TransmitFile);
            
            PlaceHolder ph = (PlaceHolder)Page.FindControl("PlaceHolder" + Convert.ToString(i));
            if (ph != null)
            {
                ph.Controls.Add(LB);
            }
        }
    }

    protected void TransmitFile(object sender, CommandEventArgs e)
    {
        LinkButton lnk = sender as LinkButton;
        var filePath = "~/Downloads/" + lnk.Text;            
        Response.ContentType = "application/octet-stream";
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + lnk.Text);            
        Response.TransmitFile(filePath);
        Response.End();
    }

For the Password side I've opted to have a login page prior to the download page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM