Opening a Word or PDF file from a webpage. C#, VS2005, APS 2.0http://forums.asp.net/t/1068814.aspx/1?Opening+a+Word+or+PDF+file+from+a+webpage+C+VS2005+APS+2+0Fri, 03 Aug 2012 03:40:17 -040010688141553397http://forums.asp.net/p/1068814/1553397.aspx/1?Opening+a+Word+or+PDF+file+from+a+webpage+C+VS2005+APS+2+0Opening a Word or PDF file from a webpage. C#, VS2005, APS 2.0 <p>Hello, I am looking for a very easy way for a user to view a word or pdf document from a webpage. On the webpage, I have user information, specifically, a filepath to a document stored on a file server that when a usert clicks a button or hyperlink, it will open that document, read only, in a separate window. I've tried a couple of things but can't get around the &quot;Download, save, abort&quot; window that pops up on server.redirect and using a hyperlink button. </p> <p>Can anyone avise me on a very easy way to achieve this? </p> <p>&nbsp;thanks.</p> <p>&nbsp;</p> 2007-01-29T14:24:19-05:001553628http://forums.asp.net/p/1068814/1553628.aspx/1?Re+Opening+a+Word+or+PDF+file+from+a+webpage+C+VS2005+APS+2+0Re: Opening a Word or PDF file from a webpage. C#, VS2005, APS 2.0 <p>You can have the page just write it out.&nbsp; Let's say they send the request to your page like this:</p> <blockquote> <p>&quot;downloadfile.aspx?file=somefile.doc&quot;</p> </blockquote> <p>Now, in downloadfile.aspx, you need to set up things like this example (though you SHOULD check to ensure they are downloading from the directory you expect!):</p> <p><a href="http://www.xefteri.com/articles/show.cfm?id=8">http://www.xefteri.com/articles/show.cfm?id=8</a></p> <p>I forgot I was on the C# forum.</p> <blockquote><pre class="prettyprint">void Page_Load ( object sender, EventArgs e ) string strRequest = Request.QueryString[&quot;file&quot;]; //-- if something was passed to the file querystring if ( strRequest != &quot;&quot; ) { //get absolute path of the file // the file is passed like a web address /images/myimage.jpg string path = Server.MapPath(strRequest); //get file object as FileInfo System.IO.FileInfo file = new System.IO.FileInfo(path); //-- if the file exists on the server if ( file.Exists ) //set appropriate headers { Response.Clear(); Response.AddHeader(&quot;Content-Disposition&quot;, &quot;attachment; filename=&quot; &#43; file.Name); Response.AddHeader(&quot;Content-Length&quot;, file.Length.ToString()); Response.ContentType = &quot;application/octet-stream&quot;; // write file to browser Response.WriteFile(file.FullName); Response.End(); } else { // if file does not exist Response.Write(&quot;This file does not exist.&quot;); } } else { //nothing in the URL as HTTP GET Response.Write(&quot;Please provide a file to download.&quot;); } }</pre></blockquote> <p>There is the example in C#.</p> 2007-01-29T16:07:18-05:001553751http://forums.asp.net/p/1068814/1553751.aspx/1?Re+Opening+a+Word+or+PDF+file+from+a+webpage+C+VS2005+APS+2+0Re: Opening a Word or PDF file from a webpage. C#, VS2005, APS 2.0 <p>Thanks for the reply!!!!&nbsp;</p> <p>I worked with this briefly, but I noticed 2 problems with this approach, <br> 1) - the downloadfile.aspx page opens, which I do not want an additional window for the user to close AND<br> 2) - the File Download dialog box opens offering the user to save, open or cancel the word document. Which I do not want, I need it to just open up the document in another page. </p> <p>It would be ideal for the user to click a button on a webpage and that would simply open word or adobe using an existing document, in a seperate window. <br> Hope this makes sense.<br> Thanks again!</p> 2007-01-29T16:59:56-05:001554695http://forums.asp.net/p/1068814/1554695.aspx/1?Re+Opening+a+Word+or+PDF+file+from+a+webpage+C+VS2005+APS+2+0Re: Opening a Word or PDF file from a webpage. C#, VS2005, APS 2.0 <p>Remove the &quot;attachment; &quot; portion of the &quot;Content-Disposition&quot; header and it should work.&nbsp; You should also send the proper mime type (text/html for HTML documents, for instance), but it is not always necessary and application/octet-stream basically lets the browser figure it out.&nbsp; Testing on my own machine with various file types, it opened up the new window and either loaded the file in the window (text, HTML), or required me to open it with the Download dialog, which closed the window when I downloaded the item.&nbsp; One case did not close the window, which was&nbsp;a PDF file using &quot;application/octet-stream&quot; but by providing &quot;application/pdf&quot; it was correctly opened in the window.&nbsp;I am running IE 7.&nbsp; Providing the mime type for the Office types (Excel's is &quot;application/vnd.ms-excel&quot; I believe) did not seem to help, but I am running the beta for Office 2007, so that might be a security feature to not display them within the browser and it still closed the window.</p> <p>For the full list of &quot;official&quot; types: <a href="http://www.iana.org/assignments/media-types/"> http://www.iana.org/assignments/media-types/</a></p> 2007-01-30T04:48:30-05:001555960http://forums.asp.net/p/1068814/1555960.aspx/1?Re+Opening+a+Word+or+PDF+file+from+a+webpage+C+VS2005+APS+2+0Re: Opening a Word or PDF file from a webpage. C#, VS2005, APS 2.0 <p>Thanks for taking the time to create this detailed resolution. Everything functions as you had mentioned. FYI, if the document to view is a .pdf, I use the application/pdf oterwise I use application/Actet-stream.</p> <p>I am now wondering if there is a way for these documents to be brought up in read-only, where the user cannot change and then&nbsp;resave&nbsp;the document. </p> <p>Is there something I can set in the code behind of the DownLoadFile.aspx page or something I can add to the Response.AddHeader?</p> <p>Thanks much for the assistance.</p> 2007-01-30T18:50:08-05:001556638http://forums.asp.net/p/1068814/1556638.aspx/1?Re+Opening+a+Word+or+PDF+file+from+a+webpage+C+VS2005+APS+2+0Re: Opening a Word or PDF file from a webpage. C#, VS2005, APS 2.0 <p>Yes, you can change the ReadOnly attribute of the file, but are you sure that this is necessary?</p> <p>The users are downloading the file from the server, and they will not be able to change the file on the server unless they have access to replace that file themselves (such as through FTP).</p> <p>It's not as though the users open the file, then click save and it overwrites the file on your server.</p> <p>Anyway, if you just wanted to make the files ReadOnly, then you can set them to be ReadOnly before sending the files by adding &quot;file.IsReadOnly&nbsp;= true;&quot; before sending the file (&quot;Response.WriteFile(file.FullName);&quot;).&nbsp; Make sure that you set it back to false, or it will stay Read Only (of course, you&nbsp; or the user can just go into the folder [that the file resides, or they download your file to]&nbsp;and right click -&gt; Properties -&gt; Uncheck Read-only to change it manually in Windows Explorer).</p> 2007-01-31T03:51:02-05:001557285http://forums.asp.net/p/1068814/1557285.aspx/1?Re+Opening+a+Word+or+PDF+file+from+a+webpage+C+VS2005+APS+2+0Re: Opening a Word or PDF file from a webpage. C#, VS2005, APS 2.0 <p>Thanks Picky. FYI, I am an old cobol programmer still adjusting to the C# switch. Your detailed answers are very helpful. The more code examples I see the better. <br> The reason I want to set the readonly attribute is simple, it is easier for me to explain to the user that, Yes, the file is readonly, aposed to explaining why the readonly is not necessary because blah, blah, blah....... </p> <p>Thanks for the help. Job well done!!!!!!!!!!!!!!!!!!</p> 2007-01-31T13:10:05-05:001558107http://forums.asp.net/p/1068814/1558107.aspx/1?Re+Opening+a+Word+or+PDF+file+from+a+webpage+C+VS2005+APS+2+0Re: Opening a Word or PDF file from a webpage. C#, VS2005, APS 2.0 <p>You're welcome, and I am glad I could help.</p> <p>Hopefully your transition to C# can be pretty painless.</p> 2007-01-31T20:26:25-05:001569704http://forums.asp.net/p/1068814/1569704.aspx/1?Re+Opening+a+Word+or+PDF+file+from+a+webpage+C+VS2005+APS+2+0Re: Opening a Word or PDF file from a webpage. C#, VS2005, APS 2.0 <p>Hi Picky</p> <p>I'm working on a similar thing to what you're discussing here, I don't want to show a download dialog, I just want the file displayed in the browser. I've got it all working at the moment, but&nbsp; I must say I don't really understand this contentType or even the attachHeader and content-disposition stuff. For example, I've used the octet-stream as the catch all because using octet-stream for pdf documents caused the adobe application to launch. Still no download dialog but it opens a new window (Adobe reader) which I don't want. But using Application/pdf, works perfectly. </p> <p>Is this because I don't specify an attach header as inline? As you can see from below, I try to identify the file type, but I don't think it's robust enough because clients may use many more file types.</p> <p>Any thoughts/comments on this would be much appreciated.</p> <p>Thanks&nbsp;</p> &nbsp;<pre class="prettyprint">public void ProcessRequest(HttpContext context) { //context.Response.Write(&quot;Hello World&quot;); String sFileName = &quot;&quot;; String sFullPath = String.Empty; sFullPath = context.Request.QueryString[&quot;FullPath&quot;]; if (sFullPath != null &amp;&amp; sFullPath.Length &gt; 4) { if (sFullPath.Contains(@&quot;\&quot;)) { if (File.Exists(sFullPath)) { FileInfo _file4View = new FileInfo(sFullPath); context.Response.Buffer = false; context.Response.Clear(); String sContentType = &quot;&quot;; switch (Path.GetExtension(sFullPath).ToLower()) { case &quot;.dwf&quot;: sContentType = &quot;Application/x-dwf&quot;; break; case &quot;.pdf&quot;: sContentType = &quot;Application/pdf&quot;; break; case &quot;.doc&quot;: sContentType = &quot;Application/vnd.ms-word&quot;; break; case &quot;.ppt&quot;: case &quot;.pps&quot;: sContentType = &quot;Application/vnd.ms-powerpoint&quot;; break; case &quot;.xls&quot;: sContentType = &quot;Application/vnd.ms-excel&quot;; break; default: sContentType = &quot;Application/octet-stream&quot;; break; } context.Response.ContentType = sContentType; MemoryStream _Stream = new MemoryStream(); //StreamWriter _writer = new StreamWriter(_Stream); FileStream _fileStream = new FileStream(sFullPath, FileMode.Open, FileAccess.Read); long fileLength = _fileStream.Length; Byte[] _byte = new Byte[(int)fileLength]; _fileStream.Read(_byte, 0, (int)fileLength); _fileStream.Close(); context.Response.BinaryWrite(_byte); } } } }</pre> 2007-02-08T12:57:12-05:001571092http://forums.asp.net/p/1068814/1571092.aspx/1?Re+Opening+a+Word+or+PDF+file+from+a+webpage+C+VS2005+APS+2+0Re: Opening a Word or PDF file from a webpage. C#, VS2005, APS 2.0 A few things jump out at me when looking at your code that do not really have to do with the download dialog. <ol> <li> <p>You do not do very much path checking to see if the requested file's location is maybe a little too close on your root drive (luckily you will probably be protected by user rights, but that's not really guaranteed).</p> </li><li> <p>You declare and instantiate your <strong>FileInfo</strong> variable for the Extension property, but you never use it (you instead use a static method from System.IO.Path; both operate the same), which is fine, but you should get rid of it or use it.</p> </li><li> <p>You go to a lot of effort to write out your file, when you could just use &quot;context.Response.WriteFile(sFullPath);&quot; or &quot;context.Response.WriteFile(_file4View.FullName);&quot; instead of using all of the streams, and the byte array.</p> </li><li> <p>Ignoring the last point, I see that you store the file's length as a long value (appropriately since the property returns a long), but then you cast it twice into an integer. It's not a big deal by any means, but you might as well store it as an integer in the first place to avoid two wasted casts right after it. Again, this is just me being, well, <em>picky</em>.</p> </li></ol> <p>As for the actual issue at hand, you don't need to add the &quot;attachment<strong>;</strong>&quot; part to the Content Disposition (similarly, you do not and should not add &quot;inline;&quot; to it, but you <em>could</em> for certain files).&nbsp; You actually do not even need to add the Content Disposition, but I think it is helpful, especially for files that may not be opened inside of the browser (such as MS Word files in my case with Word 2007 Beta), in which case it will suggest a filename for them.&nbsp; Using the headers kind of suggests dumping the use of Path.GetExtension(...) in favor of using _file4View.Extension because it will make it easier to get the file name (without the path) and the file's length easily.&nbsp; Replace Path.Get..(...).ToLower() with _file4View.Extension.ToLower(), and you should probably rename your FileInfo variable to something a little more friendly (_file4View doesn't make much sense to me, to be honest).</p> <blockquote><pre class="prettyprint">// get a better FileInfo var name too // and spit out a [hopefully] friendly file name context.Response.AddHeader(&quot;Content-Disposition&quot;, &quot;filename=&quot; &#43; _file4View.Name); // give it the file length too context.Response.AddHeader(&quot;Content-Length&quot;, _file4View.Length.ToString());</pre></blockquote> <p>To better explain the HTTP Headers, I think it would be best to read up on them since I don't think I will do you any justice, and this is one of the best explanations of <a class="" href="http://www.httpsniffer.com/http/1413.htm" target="_blank">Content-Length</a> that I have found.&nbsp; It is very short, and very to-the-point.&nbsp; Long story short, is that if you know the length, then you should tell the client.&nbsp; The same site also provides a nice explanation for <a class="" href="http://www.httpsniffer.com/http/1905.htm#sec19.5.1" target="_blank"> Content-Disposition</a>, which is to basically use it to suggest a default filename when necessary.</p> <p>I agree that both should be used.</p> 2007-02-09T05:33:01-05:001571820http://forums.asp.net/p/1068814/1571820.aspx/1?Re+Opening+a+Word+or+PDF+file+from+a+webpage+C+VS2005+APS+2+0Re: Opening a Word or PDF file from a webpage. C#, VS2005, APS 2.0 &nbsp;<pre class="prettyprint">public void ProcessRequest(HttpContext context) { String sFullPath = String.Empty; sFullPath = context.Request.QueryString[&quot;FullPath&quot;]; if (sFullPath != null &amp;&amp; sFullPath.Length &gt; 4) { if (sFullPath.Contains(@&quot;\&quot;)) { try { FileInfo _fileInfo = new FileInfo(sFullPath); if (_fileInfo.Exists) { // Clear the whatever context.Response.Buffer = false; context.Response.Clear(); String sContentType = &quot;&quot;; // Determine the content type switch (_fileInfo.Extension.ToLower()) { case &quot;.dwf&quot;: sContentType = &quot;Application/x-dwf&quot;; break; case &quot;.pdf&quot;: sContentType = &quot;Application/pdf&quot;; break; case &quot;.doc&quot;: sContentType = &quot;Application/vnd.ms-word&quot;; break; case &quot;.ppt&quot;: case &quot;.pps&quot;: sContentType = &quot;Application/vnd.ms-powerpoint&quot;; break; case &quot;.xls&quot;: sContentType = &quot;Application/vnd.ms-excel&quot;; break; default: // Catch-all content type, let the browser figure it out sContentType = &quot;Application/octet-stream&quot;; break; } // Set the headers ??? don't ask context.Response.AddHeader(&quot;Content-Disposition&quot;, &quot;filename=&quot; &#43; _fileInfo.Name); context.Response.AddHeader(&quot;Content-Length&quot;, _fileInfo.Length.ToString()); // Set the content type context.Response.ContentType = sContentType; // Write the file to the browser context.Response.WriteFile(sFullPath); } } catch (Exception ex) { MBL.HMR.Equator_Portal.BusinessLogic.utilities.LogMessageToFile(ex.Message &#43; &quot;\r\n &quot; &#43; ex.StackTrace &#43; &quot;\r\n &quot; &#43; ex.InnerException); } } } }</pre>&nbsp;<p>Yup! I agree. I have never done anything similar before, so I've got lots of trial and error code in there that I still hadn't removed. But I have implemented your suggestions and quess what... it works. I suppose the surprising thing is the fact that Response.WriteFile worked. I didn't expect that to work, because I had tried similar before and it just wrote garbled text to the screen.</p><p>Interestingly though, I have now noticed that office application documents work, but prompt first which is a user preference, pdfs work exactly the way I want, no prompt, it just shows the file. </p><p>dwf files on the other hand don't. The ProcessRequest method is called twice and the second time it's called the dwf file name has subtracted all the back slashes. So if I start as c:\\my documents\\test.dwf as the filename in the query string, I end up with c:\my documents\test.dwf the first time, and c:my documentstest.dwf the second time. I know the dwf viewer currently doesn't work reliably in internet explorer&nbsp; (mine doesn't work at all) but this is even more unusual.</p><p>As a work around I now quadruple the "\" character since I am passing this query string from a dynamically generated javascript:</p><p>&nbsp;</p><pre class="prettyprint">_visibleJscript.Append(<span class="st">"ShowMeHideMe('"</span> + drawingDiv.ClientID + <span class="st">"', '"</span> + GridViewDiv.ClientID + <span class="st">"'); "</span>); _visibleJscript.Append(<span class="st">"document.getElementById('"</span> + PreviewBox.ClientID + @<span class="st">"').src= '"</span> + Request.ApplicationPath + <span class="st">"/preview.ashx?FullPath="</span> + e.Row.Cells[9].Text.Replace(@<span class="st">"\"</span>, @<span class="st">"\\\\"</span>) + <span class="st">"';"</span>); e.Row.Cells[9].Text = <span class="st">"Image"</span>; e.Row.Cells[9].CssClass = <span class="st">"portalbutton"</span>; e.Row.Cells[9].Attributes[<span class="st">"onclick"</span>] = _visibleJscript.ToString(); </pre> <p>&nbsp; Any ideas how to check if the ProcessRequest is running for the first time, like an &quot;isPostBack&quot; type variable?</p> <p>Thanks</p> <p>Oh here's the updated ProcessRequest:</p> <p>&nbsp;</p> 2007-02-09T15:04:12-05:001571836http://forums.asp.net/p/1068814/1571836.aspx/1?Re+Opening+a+Word+or+PDF+file+from+a+webpage+C+VS2005+APS+2+0Re: Opening a Word or PDF file from a webpage. C#, VS2005, APS 2.0 <p>Sorry, my previous post came out upside down. Thanks a lot for the information you provided so far.</p> <p>There is something else I forgot to mention, this code works on the deployment machines, as well as in debug mode (while I'm actually stepping through the code ie on localhost:3020//) BUT when I run the application from localhost// whether or not the project configuration is debug or release it doesn't work at all. So identical code works on machines deployed to, but not on mine unless I am debugging the application.</p> <p>Could this have something to do with ASPnet process access rights to files, because some filehandling code I wrote before worked in the dev environment but not in production.<br> </p> <p>I used all that streams and byte array stuff because I thought I could open the file as readonly, thereby avoiding any permissions issues, but that doesn't seem to make a difference.&nbsp; The end result is that I am now worried about deploying another build to the users until I am sure this will keep working.</p> <p>Any ideas?</p> <p>Thanks&nbsp;</p> 2007-02-09T15:14:20-05:001571956http://forums.asp.net/p/1068814/1571956.aspx/1?Re+Opening+a+Word+or+PDF+file+from+a+webpage+C+VS2005+APS+2+0Re: Opening a Word or PDF file from a webpage. C#, VS2005, APS 2.0 <p>I don't think that checking to see if it's a return trip is the best approach for your DWF issues here, but I&nbsp;may have just misunderstood&nbsp;the issue.&nbsp; What you really need to do is figure out what is causing the stripped slashes and fix it&nbsp;(my guess is that it's where you are using it in JavaScript, you should be replacing @&quot;\&quot; with @&quot;\\&quot; because just like C# it needs the slash escaped).</p> <p>As for your file access problems, it is quite likely that your problem stems from the fact that ASP.NET does not have the appropriate file access to what ever you are trying to access.</p> <p>Concerning opening the files in read-only mode to beat the access issues.&nbsp; You can only open a read-only version of a file if the permissions allow you to read the file in the first place.</p> 2007-02-09T16:09:40-05:002746382http://forums.asp.net/p/1068814/2746382.aspx/1?Re+Opening+a+Word+or+PDF+file+from+a+webpage+C+VS2005+APS+2+0Re: Opening a Word or PDF file from a webpage. C#, VS2005, APS 2.0 <p>&nbsp;Hi this article was useful but I have an issue if somebody could help that would be great<br> </p> 2008-11-14T16:27:37-05:002746401http://forums.asp.net/p/1068814/2746401.aspx/1?Re+Opening+a+Word+or+PDF+file+from+a+webpage+C+VS2005+APS+2+0Re: Opening a Word or PDF file from a webpage. C#, VS2005, APS 2.0 <p>&nbsp;Hi I am importing a vb6 dll in my .net web application and I am invoking a particular fuction from the dll, when the same is done in my windows application it works perfectly but it does not work in my web application. What should I possibly do to make it work. </p> <p>Please its quite urgent, it would be great if somebody could help on this <br> </p> 2008-11-14T16:35:49-05:003104330http://forums.asp.net/p/1068814/3104330.aspx/1?Need+Souce+Code+for+find+duplicate+Images+from+a+webpage+C+VS2005Need Souce Code for find duplicate Images from a webpage. C#, VS2005 <p>I Need Souce Code for Find Duplicate Images from Server or Server Folder<br> </p> <p>Reply me</p> <p>Regards</p> <p>L.Prem&nbsp;</p> 2009-04-20T11:45:53-04:003199540http://forums.asp.net/p/1068814/3199540.aspx/1?Re+Opening+a+Word+or+PDF+file+from+a+webpage+C+VS2005+APS+2+0Re: Opening a Word or PDF file from a webpage. C#, VS2005, APS 2.0 <p>object fileName = myFilePath; <br> object readOnly = false; <br> object isVisible = true;<br> object missing = System.Reflection.Missing.Value;<br> Word.ApplicationClass oWordApp = new Word.ApplicationClass();<br> Word.Document oWordDoc = oWordApp.Documents.Open(ref fileName, <br> ref missing,ref readOnly, ref missing,<br> ref missing, ref missing, ref missing, <br> ref missing, ref missing, ref missing, <br> ref missing, ref isVisible, ref missing,<br> ref missing, ref missing, ref missing);<br> oWordDoc.Activate();<br> I got this running on my machine, then on server i.e. if application run on server itself, it opens the doc, but whenever tried from client machine, the doc opens on server and not on client. Can you please help? Thank you. </p> 2009-05-31T08:16:52-04:005093545http://forums.asp.net/p/1068814/5093545.aspx/1?Re+Opening+a+Word+or+PDF+file+from+a+webpage+C+VS2005+APS+2+0Re: Opening a Word or PDF file from a webpage. C#, VS2005, APS 2.0 <p></p> <blockquote><span class="icon-blockquote"></span> <h4>pickyh3d</h4> <p></p> <p>Remove the &quot;attachment; &quot; portion of the &quot;Content-Disposition&quot; header and it should work.&nbsp; You should also send the proper mime type (text/html for HTML documents, for instance), but it is not always necessary and application/octet-stream basically lets the browser figure it out.&nbsp; Testing on my own machine with various file types, it opened up the new window and either loaded the file in the window (text, HTML), or required me to open it with the Download dialog, which closed the window when I downloaded the item.&nbsp; One case did not close the window, which was&nbsp;a PDF file using &quot;application/octet-stream&quot; but by providing &quot;application/pdf&quot; it was correctly opened in the window.&nbsp;I am running IE 7.&nbsp; Providing the mime type for the Office types (Excel's is &quot;application/vnd.ms-excel&quot; I believe) did not seem to help, but I am running the beta for Office 2007, so that might be a security feature to not display them within the browser and it still closed the window.</p> <p>For the full list of &quot;official&quot; types: <a href="http://www.iana.org/assignments/media-types/"> http://www.iana.org/assignments/media-types/</a></p> <p></p> </blockquote> <p></p> <p>Hi pickyh3d, I have follow ur suggestion to remove attachment, and it can read a pdf file with existing web form... but it cannot open a new window or new broswer... please help</p> 2012-08-03T03:40:17-04:00