1

I have a web application in which I need to show some pdf files and word documents to the user. By clicking a button the pdf is rendered perfectly in a browser window but when I do that for .doc file it downloads and looks like this

Result of the code below

My code c# code for this is as follows

            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(FilePath);
            WebResponse myResp = myReq.GetResponse();
            //Response.AddHeader("Content-Disposition", "inline; filename=\"" + FileName + "\"");
            Response.AppendHeader("Content-Disposition", "inline; filename=\"" + FileName + "\"");
            Response.ContentType = "application/msword";
            using (Stream stream = myResp.GetResponseStream())
            {
                int count = 0;
                do
                {
                    byte[] buf = new byte[10240];
                    count = stream.Read(buf, 0, 10240);
                    Response.OutputStream.Write(buf, 0, count);
                    Response.Flush();
                } while (stream.CanRead && count > 0);
            }

Is there any way to show doc/xls/ppt files in the browser window without losing its formatting, since the server side code can't open the file in client machine using the native applications(like ms word). Isn't it possible to write file to the output stream as in the code

Arvin
  • 954
  • 3
  • 14
  • 33

2 Answers2

0

Try two different Response: myResp to get, and resp to output. See below, this works on my machine dev and prod VS 2010.

HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(FilePath);
using (HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse()) {
    using (Stream stream = myResp.GetResponseStream()) {
    HttpResponse resp = HttpContext.Current.Response;
    resp.Clear();
    resp.ContentType = "Application/msword";
    resp.AddHeader("Content-Disposition", "attachment; filename=xyz.doc");
    int count = 0;
                do
                {
                    byte[] buf = new byte[10240];
                    count = stream.Read(buf, 0, 10240);
                    resp.OutputStream.Write(buf, 0, count);
                    resp.Flush();
                } while (stream.CanRead && count > 0);
    }
}
0

You can try to use View Office documents online service from Microsoft.

Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49