File download does not work

2

How to download a file by the browser from a directory in my project?

I tried the following, but nothing happens:

 string path = "C:\test.txt";
        var file = new FileInfo(path);
        if (file.Exists)
        {
            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
            Response.AddHeader("Content-Length", file.Length.ToString());
            Response.ContentType = "text/plain";
            Response.Flush();
            Response.TransmitFile(file.FullName);
            Response.End();
        }

I debugged and the values are all correct, but do not drop anything in the browser, how do I?

<system.web>
<!-- Autenticação-->
<authentication mode="Forms">
  <forms name="login" loginUrl="login.aspx" protection="All" timeout="1" defaultUrl="pagina.aspx" requireSSL="false"/>
</authentication>
<compilation debug="true" targetFramework="4.5">
  <assemblies>
    <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
  </assemblies>
</compilation>
  <httpRuntime maxRequestLength="50000" />
<pages controlRenderingCompatibilityVersion="4.0"/>

    
asked by anonymous 18.03.2015 / 12:34

3 answers

0

@WarLock, with the knowledge I have about your application (acquired from your other questions), I believe your problem is not in the download itself, but in the UpdatePanel mechanic.

So I advise you to modify or add the ItemDataBound event to your Repeater , then register the Control for PostBack.

protected void <repeaterID>_ItemDataBound(object sender, DataListItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        var btDownload = e.Item.FindControl("<buttonID>") as Button;
        this.<scriptManagerID>.RegisterPostBackControl(btDownload);
    }
}
    
18.03.2015 / 20:35
0

I tested your code here and it works normally.

Try changing the contentType, like this:

//Response.ContentType = "text/plain";
Response.ContentType = "application/force-download";
Response.AddHeader("Content-Transfer-Encoding", "binary");
    
18.03.2015 / 12:53
0

You have some problems with your code. Even though I did not try it, have you tried it that way? I adapted the idea from here .

    Response.Clear();
    Response.ClearHeaders();
    Response.ClearContent();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
    Response.AddHeader("Content-Length", file.Length.ToString());
    Response.ContentType = "text/plain";
    System.IO.FileInfo Dfile = new System.IO.FileInfo(HttpContext.Current.Server.MapPath(path));
    Response.TransmitFile(Dfile.FullName);
    HttpContext.Current.ApplicationInstance.CompleteRequest();
    
18.03.2015 / 13:31