创建文本文件并下载 [英] Create text file and download

查看:24
本文介绍了创建文本文件并下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试写入内存中的文本文件,然后下载该文件而不将文件保存到硬盘.我正在使用 StringWriter 来编写内容:

I'm trying to write to a text file in memory and then download that file without saving the file to the hard disk. I'm using the StringWriter to write the contents:

StringWriter oStringWriter = new StringWriter();
oStringWriter.Write("This is the content");

然后我如何下载这个文件?

How do I then download this file?

这是答案的组合给了我我的解决方案.这是:

It was combination of answers which gave me my solution. Here it is:

StringWriter oStringWriter = new StringWriter();
oStringWriter.WriteLine("Line 1");
Response.ContentType = "text/plain";

Response.AddHeader("content-disposition", "attachment;filename=" + string.Format("members-{0}.csv",string.Format("{0:ddMMyyyy}",DateTime.Today)));
Response.Clear();

using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8))
{
    writer.Write(oStringWriter.ToString());
}
Response.End();

推荐答案

可以直接将数据写入响应流,而不是将数据存储在内存中然后将其发送到响应流:

Instead of storing the data in memory and then sending it to the response stream, you can write it directly to the response stream:

using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8)) {
  writer.Write("This is the content");
}

该示例使用 UTF-8 编码,如果您使用其他编码,则应更改该编码.

The example uses the UTF-8 encoding, you should change that if you are using some other encoding.

这篇关于创建文本文件并下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆