txt file opens in the browser instead of being downloaded

Asked

Viewed 202 times

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 correctly, however, instead of being downloaded, it opens on the browser screen.

Any suggestions?

  • Italo posts the header of your Action for kindness.

  • that would be it? public ActionResult geraBpa()

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);
  • I changed, but it didn’t work

  • @Italorodrigo It must be because of the mime type used, try to use a text.

2

I think that 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
{
}
  • where I enclose this code?

  • @Italorodrigo you need to adapt to your clear code kkkk, but still put with a _in front of each location where you will put your code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.