我目前正在使用 HttpResponse 从我的服务器下载文件。我已经有几个函数用于下载 Excel/Word 文件,但我无法下载我的简单文本文件 (.txt)。
对于文本文件,我基本上是将 TextBox 的内容转储到文件中,尝试使用 HttpResponse 下载文件,然后删除临时文本文件。
这是适用于 Excel/Word 文档的代码示例:
protected void linkInstructions_Click(object sender, EventArgs e)
{
String FileName = "BulkAdd_Instructions.doc";
String FilePath = Server.MapPath("~/TempFiles/BulkAdd_Instructions.doc");
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/x-unknown";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
}
这是不起作用的代码块。
请注意,代码运行时不会引发任何错误。文件已创建并删除,但从未转储给用户。
protected void saveLog(object sender, EventArgs e)
{
string date = DateTime.Now.ToString("MM_dd_yyyy_hhmm"); // Get Date/Time
string fileName = "BulkLog_"+ date + ".txt"; // Stitch File Name + Date/Time
string logText = errorLog.Text; // Get Text from TextBox
string halfPath = "~/TempFiles/" + fileName; // Add File Name to Path
string mappedPath = Server.MapPath(halfPath); // Create Full Path
File.WriteAllText(mappedPath, logText); // Write All Text to File
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
response.TransmitFile(mappedPath); // Transmit File
response.Flush();
System.IO.File.Delete(mappedPath); // Delete Temporary Log
response.End();
}