File txt opens in the browser instead of being downloaded

0

I use the following code to generate a txt file and send it to my View :

 public ActionResult geraBpa(){
    var caminho = System.Web.HttpContext.Current.Server.MapPath("~/Content");
    using(StreamWriter file = new StreamWriter($"{caminho}/BPA.txt"))
    {
        List<bpac> listaBpac = pegaBpac();

        int linhaTexto = 1;
        int linhaItem = 1;

        foreach (bpac linha in listaBpac)
        {
            file.WriteLine(
            "02" +
            linha.cnes +
            linha.cmp + //competencia
            linha.cbo +
            string.Format("{0:000}", linhaTexto) + string.Format("{0:00}", linhaItem) +
            linha.pa +
            "000" +
            string.Format("{0:000000}", linha.quant) +
            "EXT"
            );

            linhaItem++;
            if (linhaItem > 99)
            {
                linhaItem = 1;
                linhaTexto++;
            }
        }
    }

    linhaTexto++;
    linhaItem = 1;

    byte[] fileBytes = System.IO.File.ReadAllBytes($"{caminho}/BPA.txt");
    string fileName = "myfile.ext";
    return File(fileBytes, MediaTypeNames.Application.Octet, fileName);
}

The same is working properly, however, instead of being downloaded, it opens on the browser screen.

Any suggestions?

    
asked by anonymous 22.08.2017 / 19:58

2 answers

3

You can add a header to force this download

// [...] Resto do código

string fileName = "myfile.ext";
var disposition = new System.Net.Mime.ContentDisposition
{
    FileName = fileName,
    Inline = false, // <- Isso força o download
};

Response.AppendHeader("Content-Disposition", disposition.ToString());

return File(fileBytes, MediaTypeNames.Application.Octet, fileName);
    
22.08.2017 / 20:05
2

I think this would solve your problem:

try
{
    Response.Clear();
    Response.ClearHeaders();
    Response.ClearContent();
    Response.AddHeader("content-disposition", "attachment; filename=" + _Filename);
    Response.AddHeader("Content-Type", "application/Word");
    Response.ContentType = "application/octet-stream";
    Response.AddHeader("Content-Length", _FileLength_in_bytes);
    Response.BinaryWrite(_Filedata_bytes);
    Response.End();
}
catch (ThreadAbortException)
{ }
finally
{
}
    
22.08.2017 / 20:04