This project is read-only.

Forcing the download of a SharePoint Document

Feb 25, 2011 at 8:57 PM

Hi!

 

I have created a web part using code suggested in this web site

http://vspug.com/jscott/2008/12/19/forcing-the-download-of-a-sharepoint-document/

The web part works fine. It forced to download the file and save it at destination location. But there is one problem and here it is. We are using a fillable PDF Version 9 Form. The Web Part download this file and save it at a destination location. But tis file is always corrupted. When we try to open the file it does not open and get the message it is corrupted. So during the downloading process the file is corrupted. This happened with Fillable PDF version 9 file. However other older PDF files have no problem. My Web Part code is listed below. Any help to resolve this issue will be highly appreciated. Thanks in advance. Tayyab

private void DownloadFile(string fileName)
        {
            try
            {
                string path = System.Web.HttpContext.Current.Server.MapPath(fileName);
                string name = System.IO.Path.GetFileName(path);

                Microsoft.SharePoint.SPFile spFile =
                    Microsoft.SharePoint.SPContext.Current.Web.GetFile(fileName);

                Page.Response.ClearHeaders();
                Page.Response.ClearContent();

                Page.Response.ContentType = "application/pdf";
                Page.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name.ToString());
                byte[] bFile = spFile.OpenBinary(SPOpenBinaryOptions.SkipVirusScan);
                Page.Response.OutputStream.Write(bFile, 0, bFile.Length);
                Page.Response.Flush();
                System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
                                                          }
            catch (Exception ex)
            {
                Page.Response.Write("Message: ");
                Page.Response.Write("<br/>");
                Page.Response.Write(ex.Message);
                Page.Response.Write("<br/><br/>");
                Page.Response.Write("StackTrace: ");
                Page.Response.Write("<br/>");
                Page.Response.Write(ex.StackTrace);
                Page.Response.End();
            }
        }

PS: One funny thing if I add this code to the page using SharePoint Designer it works fine.