Programmatically Downloading Text Files using C# RRS feed

  • Question

  • User2036625791 posted
    Hello, I am generating formatted text on the backend via a button click from a web form. Once text generation has completed I am sending the file back to the browser using the HttpResponse object from the page I received the event from. I have a function called StreamText which reads a file line by line and writes these lines to the HttpResponse.Output property. The normal behavior would be to receive the text file that I generated. The text files contains the complete HTML code of the page in addition to the formatted text I have generated. I have searched on the Internet for reasons why this is happening but I have not found anything. Any assistance will be greatly appreciated and I have posted code below. Binary files appear to work fine. Thanks, William Mapp // code public static void StreamFile(string path, HttpResponse response) { FileUtility.WriteFile("doc.explore.txt", "\r\nFileManagementProxy.StreamFile - Writing the file : " + path, true); response.Clear(); response.AddHeader("Content-Disposition", "attachment; filename=" + FileManagementProxy.GetCanonicalFilename(path)); if(path.IndexOf(".txt") != -1 || path.IndexOf(".out") != -1 || path.IndexOf(".text") != -1 || path.IndexOf(".xml") != -1) { FileUtility.WriteFile("doc.explore.txt", "\r\nFileManagementProxy.StreamFile - Content-Type: text/plain", true); response.ContentType = "text/plain"; StreamText(path, response); } else { response.ContentType = "application/octet-stream"; StreamBinary(path, response); } } private static void StreamText(string path, HttpResponse response) { FileUtility.WriteFile("doc.explore.txt", "\r\nFileManagementProxy.StreamText - Streaming text file: " + path, true); FileStream fs = new FileStream(path, FileMode.Open); StreamReader sr = new StreamReader(fs); string line = null; while((line = sr.ReadLine()) != null) { if(response.IsClientConnected) { response.Output.WriteLine(line); } } sr.Close(); fs.Close(); }
    Tuesday, August 31, 2004 10:40 AM

All replies

  • User1694595804 posted
    Response.End(); http://www.bestcomy.net download the aspnetupload 2.0 demo and you will get a large file download sample in the source.
    Friday, September 24, 2004 9:52 AM
  • User69449789 posted
    Just Response.Redirect("") the user to the textfile. Browsers tend to be even more complient to ASCII text standards as they are HTML ;) If you don't want the browser to render the text file and would rather force the user to download it, you can try this: Response.ClearContent(); Response.ClearHeaders(); Response.AppendHeader("content-disposition","attachment; filename="+file.GetName); Response.ContentType = Mime.GetMIME("doc"); Response.WriteFile(result); Response.End(); You will need to play around with this some, and change the mime type up accordingly, if you want the "Download and Save As" dialog to pop up.
    Thursday, October 14, 2004 11:25 AM