Write to txt

Asked

Viewed 68 times

1

Friends, I am trying to generate a txt, in which the user clicks on the button and automatically downloads it. It is already generating txt, but I would like to know how to write in 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();
  • File.WriteAllText("arquivo.txt", "Texto a ser escrito...");

1 answer

1


Try it like 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();
  • exactly that, it worked!! Thank you!

  • Hug, tmj. :)

Browser other questions tagged

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