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(); }
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.
None
0 Points
1 Post
Programmatically Downloading Text Files using C#
Aug 31, 2004 10:40 AM|willmapp|LINK
None
0 Points
26 Posts
Re: Programmatically Downloading Text Files using C#
Sep 24, 2004 09:52 AM|comy|LINK
None
0 Points
3 Posts
Re: Programmatically Downloading Text Files using C#
Oct 14, 2004 11:25 AM|MagicWishMonkey|LINK