创建文本文件,并下载 [英] Create text file and download
本文介绍了创建文本文件,并下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图写入到内存中的文本文件,然后下载文件,而无需将文件保存到硬盘。我使用了的StringWriter
写的内容:
的StringWriter oStringWriter =新的StringWriter();
oStringWriter.Write(这是内容);
我如何再下载此文件?
编辑:
这是这给了我答案的解决方案组合。在这里,它是:
的StringWriter oStringWriter =新的StringWriter();
oStringWriter.WriteLine(1号线);
Response.ContentType =text / plain的;Response.AddHeader(内容处置,附件;文件名=+的String.Format(社员{0} .csv,下载的String.Format({0:DDMMYYYY},DateTime.Today)));
Response.Clear();使用(StreamWriter的作家=新的StreamWriter(Response.OutputStream,Encoding.UTF8))
{
writer.Write(oStringWriter.ToString());
}
到Response.End();
解决方案
而不是存储在内存中的数据,然后将其发送到响应流中,你可以直接将其写入响应流:
使用(StreamWriter的作家=新的StreamWriter(Response.OutputStream,Encoding.UTF8)){
writer.Write(这是内容);
}
该示例使用UTF-8编码,你应该改变,如果你使用的是一些其他的编码。
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?
EDIT: 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");
}
The example uses the UTF-8 encoding, you should change that if you are using some other encoding.
这篇关于创建文本文件,并下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文