I am currently using HttpResponse to download files from my server. I already have a couple of functions used to download Excel / Word files, but it's hard for me to get my simple text file (.txt) to load.
With a text file, I basically dump the contents of the TextBox into a file, trying to load the file from HttpResponse, and then delete the temporary text file.
Here is an example of my code that works for Excel / Word documents:
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(); }
And here is a piece of code that doesn't work.
Whereas the code works without any errors. The file is created and deleted, but never dumped to the user.
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(); }
Lando
source share