Download or save file to the client from ASP C #

2

In ASP.NET with the C # language.

I need to somehow make my application download or preferably save on the client side an XML that is generated in my application.

  

In other words, in a "Download" or "Save" button you can download the XML on your computer.

Thank you in advance.

    
asked by aquiso 11.11.2016 в 23:18
source

3 answers

4

Good morning, here I leave the code behind (Code Behind), in the part of .ASPX you must add a button that says download and the click event you add this code.

private void ButtonDescargar_click(object sender, System.EventArgs e)
{
    Response.ContentType = "text/xml";
    Response.ContentEncoding = System.Text.Encoding.UTF8;
    Response.AppendHeader("NombreCabecera", "MensajeCabecera");
    Response.TransmitFile(Server.MapPath("~/tuRuta/TuArchivo.xml"));
    Response.End();
}

You can also use the function in other events, if you wish, you do not have to limit yourself to a button

    
answered by 11.11.2016 / 23:33
source
0

It also adds the following attribute to the header of the response:

// Establecer atributos de cabecera
response.AddHeader("Content-Disposition",
string.Format("attachment; filename = \"{0}\"", System.IO.Path.GetFileName(userFileName)));

The "Content-Disposition" attribute with an "attachment" value will make it safer for the browser to interpret the response as an attachment to save.

Internet Explorer 11 will load the xml as a string in a new browser tab if you do not add the "attachment" attribute.

    
answered by 17.11.2016 в 10:46
-1
<Triggers>
    <asp:PostBackTrigger ControlID="btn_Exc" />
</Triggers>
protected void btn_Exc_Click(object sender, EventArgs e)
{
    string ruta;
    ruta = Server.MapPath("~/Archivos/DOCUMENTOS_ADJUNTOS/Formato_Programacion/Formato_Programacion.xlsx");
    DescargarDocumento(ruta);
}
private void DescargarDocumento(String ruta)
{
    try
    {
        String prueba;
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ContentType = "xlsx";
        prueba = Path.GetFileName(ruta).ToString();
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + prueba);
        HttpContext.Current.Response.TransmitFile(ruta);
        HttpContext.Current.Response.End();
    }
    catch (Exception ex)
    {
        ControlarExcepcion(ex);
    }
}
    
answered by 11.09.2018 в 00:03