【发布时间】:2009-02-17 11:45:46
【问题描述】:
是否有任何方法可以获取 StreamWriter 并将文件(在本例中为 .txt 文件)输出给用户,并且可以选择打开/保存而不将文件实际写入磁盘?不保存的话基本就没了。
我正在寻找与
相同的功能HttpContext.Current.Response.TransmitFile(file);
但无需将任何内容保存到磁盘。谢谢!
【问题讨论】:
是否有任何方法可以获取 StreamWriter 并将文件(在本例中为 .txt 文件)输出给用户,并且可以选择打开/保存而不将文件实际写入磁盘?不保存的话基本就没了。
我正在寻找与
相同的功能HttpContext.Current.Response.TransmitFile(file);
但无需将任何内容保存到磁盘。谢谢!
【问题讨论】:
试试System.IO.MemoryStream
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.StreamWriter sw = new System.IO.StreamWriter(ms);
sw.Write("hello");
【讨论】:
我最近做了一个 XML 文件,应该很容易适应
protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.AppendHeader("content-disposition", "attachment; filename=myfile.xml");
Response.ContentType = "text/xml";
UTF8Encoding encoding = new UTF8Encoding();
Response.BinaryWrite(encoding.GetBytes("my string"));
Response.Flush();
Response.End();
}
【讨论】:
或使用 Response.BinaryWrite(byte[]);
Response.AppendHeader("Content-Disposition", @"Attachment; Filename=MyFile.txt");
Response.ContentType = "plain/text";
Response.BinaryWrite(textFileBytes);
类似的东西应该可以。如果您在流中有文本文件,则可以轻松地从中获取 byte[]。
编辑:见上文,但明显更改 ContentType。
【讨论】: