Response.WriteFile vs Response.Write

Hey guys...

 I am using a FileUpload control and trying to display the pdf file. I can't get it to show the pdf file when I use Response.Write. But if I save the file to a directory and use WriteFile instead I can get it to work.

 What does WriteFile do differently?


Response.ContentType = "application/pdf";

byte[] arrBytes = new byte[fUpload.PostedFile.ContentLength];Stream oStream = fUpload.FileContent;

oStream.Read(arrBytes, 0, arrBytes.Length);

new ASCIIEncoding().GetString(arrBytes));



1/15/2008 5:08:49 PM 91979 articles. 4 followers. Follow

5 Replies

Similar Articles

[PageSpeed] 21
Get it on Google Play
Get it on Apple App Store

 response.writefile is for displaying a files contents, it requires a file to read from. Response.write simple writes text to the page.

Jeff Turner (simpleModus)

Don't forget to mark the correct answer for your
question to help out future visitors!
1/15/2008 5:39:02 PM

I found the answer to my own question! I needed to use a BinaryWriter to the page. But what is the difference between BinaryWrite and using the GetString method as shown above?


Response.ContentType =




1/15/2008 5:39:57 PM

Response.Write : You write a string into the Response Object

Response.WriteFile: Used for sending file to the client machine (download). It buffers the file into the server's Memory.

I recommend using Response.TransmitFile


Haissam Abdul Malak
| Blog |
1/15/2008 7:14:46 PM

Well, using BinaryWriter, everythinig goes thru ASP.NET, not allowing you to use some of the streaming features of IIS. WriteFile uses those features and doesn't get handled by ASP.NET.

 This is importent when handling larget files!

Be sure to check out Searching a bit on the topic gives you a lot of information.

Also visit my website.

Once your questions have been answered, remember to mark the question as answered, this rewards the people helping you and helps others to move on to the next unanswered question.
1/15/2008 8:38:35 PM

This article was exactly what I was looking for. I was hoping to find someone who has actually coded each method from scratch and compared the code, but that almost sounds too good to be true. Thanks. 

1/22/2008 3:21:06 PM

Similar Artilces:

Response.WriteFile VS Buffering with Response.OutputStream
Hi all,  This is quit challenging issue! Microsoft has published that there might be a problem to download  large files when the implementation is based on  Response.WriteFile (or Response.Write…) on some hardware configurations.  In order to avoid that issue, the same article recommends using buffering. IE works fine in both cases, but unfortunately, FF seems to have a problem with the buffering. The file is downloaded but the first link you try navigating to gets "XML Parsing Error: not well-formed" (pressing...

Response.writefile, response.write and file downloads...?
I have a page which presents a file for download.Before offering the download I check it exists using  Response.ClearContent();                Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName); if(System.IO.File.Exists(TargetDirectory + "\\" + FileName))                    Response.WriteFile(TargetDirectory + "\\" + FileName);  else throw...

How can I get a Response.Write and Response.Redirect to work one following the other?
I have a button on my webform that needs to perform 2 operations.  First it must open a new window which I usually do like this: sJScript = "<script>'Form01.aspx?ID=0&Parent=5', '', '');</script>"Response.Write(sJScript)Second it must redirect the current page (not the newly opened one).  I usually do that like this:Response.Redirect("Form02.aspx?ID=6")My problem is, in this case, I must do both with one button click and they interfere with each other.  I've tried flushing/ending the response object in various places, re ordering things, etc but n...

What’s the difference between Response.Write() and Response.Output.Write()?
Response.Write() gives a formated output OR Response.Output.Write() gives a formated output. Friend, The difference between Response.Write() and Response.Output.Write() in ASP.NET. The short answer is that the latter gives you String.Format-style output and the former doesn't. The long answer follows.In ASP.NET the Response object is of type HttpResponse and when you say Response.Write you're really saying (basically) HttpContext.Current.Response.Write and calling one of the many overloaded Write methods of HttpResponse. Response.Write then calls .Write() on it's internal Text...

Response.write or Response.redirect?
I have a code using Response.Write and javascript to open another page, the code looks like this: Response.Write("<Script language='javascript'>'" & Session("varflag") & "&vid=" & Session("FacilityID") & "&vrepid=" & Session("varid") & "');</script>") it send me to another page in a different window or tab. I want to open it in the same window or tab as in Response.Redirect, but in Respons...

Response.AppendHeader AND Response.WriteFile
Hello everybody, i have a little problem to use these functionnalities. I create a text file through an asp .net webform (vb .net). Datas are a list of phone number. When i use the code below, i have the window to save as my file on my hard drive (for example). When i browse this text file, i get my list of those phone numbers and the entire HTML code just behind. Try Response.Clear() Response.ContentType = "application/octet-stream" Response.AppendHeader("content-disposition", "attachment; filename="&FileName) '...

Response.Redirect after response.OutputStream.Write?
I'm using the Wrox Docs module from Building An ASP.NET Intranet. This code outputs the doc from the DB to the client Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim ItemID As Integer = -1 Dim strTable As String = "parent" Dim DocsSec As New WroxDocSecurity() 'comment this code if you don't want to lock down the download process If Not (DocsSec.HasDocPermissions(DocumentPermissions.DownloadandViewOnly, Request.Params("key"))) _ ...

Not able to use Response.write for writing to Excel, when using Response content compression
We have the Excel download option for our page, for which we use Response.ContentType as application/ and writing the data to Excel stream using Response.write.  As we apply Respone fileter for compressing the response content, this is not working. Considering the performance we don't want to disable the compression.  can anyone give some suggestions? Thanks in advance.     Disabling the compression for these particular requests would be OK, wouldn't it?However, a compressing response filter should not be a problem, even with application/vnd....

How to use response.transmitfile or response.writefile ?
I'm accessing an excel file stored in an image field in a database. I want to write it out to a folder. DocumentSize = (int)dr["Size"]; byte[] BytesBuf = new byte[DocumentSize]; BytesBuf = (byte[])dr["Content"]; Response.Clear();Response.ContentType = "application/"; Response.OutputStream.Write(BytesBuf, 0, DocumentSize); Response.AppendHeader("Content-Disposition", "attachment; filename=out.xls"); Response.TransmitFile(System.IO.Path.Combine(Server.MapPath("~/Documents"), "out.xls")); ...

UpdatePanel and Response.Write / Response.TransmitFile
I think I may be missing something obvious here, there are many posts about not using Response.Write to write to the page within an UpdatePanel. But how can I generate and transmit a file to the client while inside an UpdatePanel? For example, a page might be laid out like this:<Updatepanel><Selection Controls><Button><Table/></UpdatePanel>The purpose of the Button is to allow the client to simply export the data from the table:    Protected Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button.Click  &nbs...

Problem with .net elements in Response.Write
I need to do a response.write on an aspx page in , where as the response.write will display on "if" condition. I'm trying to display an Iframe that contains another file, with querystring parameters. Even when I double up/escape the quotation marks, still get a "String constants must end with a double quote" error on this line: <%= response.write("<IFRAME src=banners/nv-A1List.aspx?zone=<%=request.querystring(""zone"")%> name=banner width=234 height=60 frameborder=no border=0 MARGINWIDTH=0 MARGINHEIGHT=0 SCROLLING=no>...

Response.write and response.redirect working together.
In my If then else statement I have 2 statements that are if true i need to pop up a message box and then when they hit ok, redirect them to another page.  so here is the statements and below that it show how I tried to use some code in the statment, but what happens is on the second statement the pop-up will not come up but it will wait 10 seconds and then redirect itself. ElseIf txtStatus.Text = "AGR PERM" Or txtStatus.Text = "AGR TEMP" Then       Page.RegisterStartupScript("LoadFunction", "<script type='text/ja...

Response.Redirect & Response.Write issues
I have code in my image click event which opens a new window when the end user clicks on the image. I need a new page/tab to open up and below is one version of how i do it. The issue l have is this always get stopped by the popup blocker and l want it to open up a new tab without forcing the popup or loosing the initil page!! protected void ImageButton1_Click(object sender, ImageClickEventArgs e) { Code here connects to Access and does its job then below is actioned......... try { conn.Open(); sdc.ExecuteNonQuery(); string url = ""; Response.Write(""); Response.Write("parent.framename.location.replace('url');"); Response.Write(""); } } Any thoughts anyone!!!! Paul BishopP. Bishop Try to use the below code instead Page.ClientScript.RegisterStartupScript(this.GetType(),"open","'"+url+"');",true); Hope this helps,Haissam Abdul MalakMCAD.NET| Blog | The above script, reacted in exactly the same way, the popup blocker stopped the page from opening.... There must be some way of incorporating "_blank"? Thanks so far though BishP. Bishop As far as I know, if you use, the popup blocker will hit you.  Here is a simple article that shows how to detect pop up blockers. Maybe you...

Using Response.OutputStream.Write for Sending Response to the client
 Hi All, I have a small program that is trying to POST and XML to an aspx web page. I am using WebRequest and WebResponse classes for communication between aspx and client program. Communication from client to aspx page has no problems and I am able to read complete XML file. To send a response back to the client ( a c# program) I create an XML file and convert it into byte stream and I use Response.OutputStream.Write() function to send message. On the client end I receive the message but it is followed by some standard HTML text (which is required for the aspx page. ...

Response.TransmitFile, Response.WriteFile does not continue executing the page.
Hi,  I've been battling with this problem all morning, so I'm hoping someone can help me. Essentially, I need my page to continue executing after a file has been opened or downloaded.  I have tried using Response.TransmitFile and Response.WriteFile and combined them with combinations of Response.Flush, Response.Close and Response.End, but the code following the document opening never fires, and the changes to controls (changes to label text and visibility of buttons) that I have place in the preceeding code don't get rendered either. The code I currently have is shown below but what I want to know is: How can I open a document (PDF in this case) and complete the rendering of the page? Response.Clear();Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);Response.AddHeader("Content-Length", file.Length.ToString());Response.ContentType = "application/pdf"; //write file to browserResponse.TransmitFile(file.FullName);HttpContext.Current.ApplicationInstance.CompleteRequest(); Many thanks in advance. Interesting. All of a sudden an application I have is having this problem today as well.  I get a communication error for my file downloads that are approximately larger than 45mb or so.  The application had been previously working for months just fine. I haven't changed any code.  Here is my code, pretty much the same:   Response.Clear(...

get text of Response.Write
hi i tried to use an Exif Reader Library. have the sample code as belowvoid ShowImageExif()    {        string filename = MapPath("~/IMG_0230.JPG");        System.Drawing.Bitmap b = new System.Drawing.Bitmap(filename);         Goheer.EXIF.EXIFextractor er = new Goheer.EXIF.EXIFextractor(ref b, "\n");        Response.Write(er); //show all data        Response.Write(er["Date Time"]); //to read the Date Tim...

No response from response.redirect
Hi, my project has atleast 10 webforms and for navigation the response.redirect was working fine till today. It stopped working in one of the pages but stills fine in the other pages. eg. the CANCEL button loads the previously navigated page. All CANCEL except one are working. I checked the button click event, put labels with messages in them; the labels get posted when the button is clicked; but when i remove the labels and put in the response.redirect("PAGE NAME") it stopped working; i even put the wrong path in the response.redirect, still the errorhandler or any o...

response.write vs label
Hi, I am starting a new web site. In ASP I always outputted data from the database using response.write. With .NET I suppose I can use that or I can also apply the data to a label.text for output. Anyone have feelings on which method they think is better in the long run? Paul response.write will cause items to be sent outside the rest of the page. i.e. if your processing a complex page and send a few response.writes that should be in the middle of the page, the client gets the response.writes first and then the rest of the .Net pieces after. response.write has uses, b...

Getting content from http response ? (http-on-examine-response)
Hi everyone, I'm writing an extension that inspects the http response content received from one given http server. So far I've tried to use the notification "http-on-examine-response" mechanism which allows me to inspect http headers from the response, but I don't have access to the actual content of the response. Indeed, you only have access to the nsIHttpChannel interface, which only has methods to get the headers. Could anyone point me to the right direction on how to access the http content please ? Thanks in advance, Best regards, Mfenetre wrote: ...

Using Response.Redirect and Response.Write from flat class file
Setup: I developed an interface that holds certain functions that are shared between some users in my system. The different users are grouped into classes that implement that interface. Problem: In some instances the implementations of this interface include a mere write to the screen or a redirect. However, when I attempt to do something like Response.write or Response.redirect from those classes, I am getting an error that says "Response is not Available in this Context" Question: Is what I am trying to do possible and if so, how do I correct this problem. ...

Response.TransmitFile or Response.WriteFile non blocking calls problem
I have an ASP.NET 2.0 application in VB. The application decrypts a file, stores it as a new file, and sends the decrypted file to the client. I want the application to wait until the transfer is complete and then delete the decrypted file. I tried to use response.transmitfile and response.writefile but they are non blocking calls and IIS takes over and the application doesnt wait for the transfer to finish. Is what I need possible? Hi,You don't have to write the decrypted data into a file first. Why don't you keep it in memory?Please refer to this artilce:http:/...

getting Panels to work with Response.Write()
I am using panels to with my contents with and realised that when I use Response.Write(), the <asp:panel> does not translate into <div> tags on the client side. My test code in test.aspx are: <asp:panel runat="server">test<br /></asp:panel> <% Response.Write("<asp:panel ID=\"Panel1\" runat=\"server\">test<br /></asp:panel>"); %> When it gets loaded in a browser, the source of the test.aspx page shows the following:    <div> test<br /> <asp:panel ID="Panel1" runat="server">test<br />&l...

using response.write and .net datareader
Hi, Is it possible to specify the actual name of the data using a .net datareader (to get data from a sql server database)? Ideally I would like to be able to do : response.write (reader("ProjectName")) is this the write syntax?  Also is it possible to create a string based on the data name myString=reader("ProjectName")   Many thanks Mark :)  You can refer to the column name like this example (and yes you can use the same method to set a variable):  While MyDataReader.Read Response.Write("Name: " & MyDa...

Could not get the Behaviour of my Response.Write() method
Hi I am trying to develop a very basic application in AJAX. Here the browser sends a request to the Server... the server upon receiving the request sends a string(through Response.Write(strTest))... then the browser is supposed to read the string and assigns the value to a textbox..... But the string is not being assigned to the Now here is where I think the problem is.... Though the browser reads the server's response, I find that (on displaying the string through an alert) the entire HTML file has been appended after the string supposed to be sent.... Is it something t...

Web resources about - Response.WriteFile vs Response.Write -

Let's Play TDD #158: writeFile
12 Jan 2012 James Shore/Blog/Lets-Play The source code for this episode is available here . Visit the Let's Play archive for more episodes! ...

Named pipe - Wikipedia, the free encyclopedia
In computing , a named pipe (also known as a FIFO for its behavior) is an extension to the traditional pipe concept on Unix and Unix-like systems, ...

Vim: starting.txt
Quick links: help overview · quick reference · user manual toc · reference manual toc · faq starting.txt For Vim version 7.4. Last change: 2013 ...

A Handmade Executable File
Make a Windows program by stuffing bytes into a buffer and writing it to disk: no compiler, no assembler, no linker, no nothing! It was the obvious ...

Easier Testing Using the SRP
... { fileChangeNotifications = new ArrayList (); } @Before public void createFileAndMonitor() throws IOException { FileUtils.writeFile(FILENAME, ...

Android Game Development tutorial [ Part 4 ]
package com.pocogame.framework;public interface Audio { public Music createMusic(String file); public Sound createSound(String file);} package ...

My First Data Art: NYC Taxi Defrag
In my data visualization NYC Taxis: A Day in the Life , there is a D3 chart at the bottom of the screen that shows when the vehicle has a fare, ...

SD/SDHC Card Interfacing with ATmega8 /32 (FAT32 implementation)
Hi friends, Here is my project on interfacing of SD Card (microSD). microSD cards are available very cheap nowadays, a great option for having ...

Greg K. « Dropbox Forums
Dropbox Forums Sign in Search: Profile Favorites Dropbox Forums » Greg K. » Profile Greg K. Member Since April 27, 2011 (3 years) User Activity ...

Taking Toddler Steps with Node.js – The Towering Inferno Revisited
... (-1 == favoritePodcasts.indexOf( 'Astronomy Podcast' ) { favoritePodcasts = favoritePodcasts + '\n' + 'Astronomy Podcast' ; fileSystem.wri ...

Resources last updated: 2/18/2016 6:10:10 PM