创建供用户下载的文本文件 [英] Create Text File for User to Download
问题描述
我的网络应用程序应该创建一个文本文件并提示用户将其保存在本地某处。
My web app is supposed to create a text file and prompt the user to save it somewhere locally.
但我遇到的问题是我需要网络应用程序有一个临时位置,它可以在提示用户下载之前保存文本文件。
But the problem I am having is I need the web-app to have a temporary location where it can save the text file before prompting the user to download it.
网络应用程序在哪里可以保存临时文件?
Where can a web-app save a temporary file?
这是我到目前为止的代码(可能还没有正确的地方,我试图在内存中创建它而不是先保存它,但我认为我不能这样做):
Here is the code I have so far (which probably isn't right yet where I was trying to create it in memory instead of saving it first, but I don't think I can do it this way):
string gentextfilename = "Friendly.txt";
string gentext = "By George, we've done it!";
Response.ClearContent(); 
Response.ClearHeaders();
Response.ContentType =" text / plain" ;;
//" .htm"," html" =" text / html"
Response.AppendHeader(" content-disposition"," attachment; filename =" + gentextfilename);
byte [] btgentext = new byte [gentext。长度];
//Response.AppendHeader("content-length" ;, gentext.Length);
//Response.BinaryWrite(System.Text.UTF8Encoding.UTF8.GetBytes(gentext));
Response.BinaryWrite(btgentext);
Response.Flush();
Response.End();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "text/plain";
//".htm", "html" = "text/html"
Response.AppendHeader("content-disposition", "attachment; filename=" + gentextfilename);
byte[] btgentext = new byte[gentext.Length];
//Response.AppendHeader("content-length", gentext.Length);
//Response.BinaryWrite(System.Text.UTF8Encoding.UTF8.GetBytes(gentext) );
Response.BinaryWrite(btgentext);
Response.Flush();
Response.End();
推荐答案
您好BGMcoder,
Hi BGMcoder,
我们可以使用FileStream生成带有如下内存流的临时txt文件:
We can use FileStream to generate a temp txt file with the memory stream like below:
using (var fs = new FileStream(@"C:\test.txt", FileMode.Create, FileAccess.ReadWrite))
{
TextWriter tw = new StreamWriter(fs);
tw.Write("Hello World");
tw.Flush();
}
谢谢
最好的问候
这篇关于创建供用户下载的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!