Write in txt

0

Friends, I'm trying to generate a txt, in which the user clicks the button and automatically downloads it. You are already generating txt, but would you like to know how to write it?

   string str = "testando";
   byte[] bytes = new byte[str.Length * sizeof(char)];
   System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0,bytes.Length);
   MemoryStream mem = new MemoryStream();
   mem.Write(bytes, 0, str.Length);

   Stream outStream = Response.OutputStream;
   Response.ContentType = "application/text/plain";
   Response.AppendHeader("Connection", "keep-alive");
   Response.AppendHeader("Content-Disposition","attachment; filename = " + "teste.txt");
   mem.WriteTo(outStream);
   outStream.Close();
    
asked by anonymous 14.12.2018 / 13:15

1 answer

1

Try this:

byte[] bytes;

using (MemoryStream memoryStream = new MemoryStream())
{
    using (TextWriter textWriter = new StreamWriter(memoryStream))
    {
        //Altere para o texto que deseja ter no seu arquivo .txt
        textWriter.WriteLine("Teste 1");
        textWriter.WriteLine("Teste 2");
        textWriter.Flush();

        bytes = memoryStream.ToArray();
    }
}

Response.Clear();
Response.ContentType = "application/force-download";

//Altere o "nomeArquivo" para o nome do arquivo que você desejar
Response.AddHeader("content-disposition", "attachment; filename=nomeArquivo.txt");
Response.BinaryWrite(bytes);
Response.End();
    
14.12.2018 / 13:47